@PropertySource
@PropertySource 注解用于指定资源文件读取的位置,它不仅能读取 properties 文件,也能读取xml文件,并且通过 YAML 解析器,配合自定义 PropertySourceFactory 实现解析YAML文件。
@Component
@PropertySource(value = {"demo/props/demo.properties"})
public class ReadByPropertySourceAndValue {
...
}
@SuppressWarnings("ConfigurationProperties")
@Component
@ConfigurationProperties
@PropertySource(value = "classpath:code-message.properties", encoding = "UTF-8")
public class CodeMessageConfiguration {
...
}
示例:
package com.itha.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
/*
等同于
<context:property-placeholder location="classpath*:jdbc.properties"/>
*/
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
/*
使用注入的形式,读取properties文件中的属性值,
等同于<property name="*******" value="${jdbc.driver}"/>
*/
@Value("${jdbc.driverClassName}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String userName;
@Value("${jdbc.password}")
private String password;
/*定义dataSource的bean,
等同于<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
*/
@Bean("dataSource")
public DataSource getDataSource(){
//创建对象
DruidDataSource ds = new DruidDataSource();
/*
等同于set属性注入<property name="driverClassName" value="driver"/>
*/
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(userName);
ds.setPassword(password);
return ds;
}
}
@Value
@Value(“#{}”) 表示SpEL表达式通常用来获取bean的属性,或者调用bean的某个方法。当然还有可以表示常量。
@Value(“${}”) 注解从配置文件读取值。
@RestController
@RequestMapping("/login")
@Component
public class LoginController {
@Value("#{1}")
private int number; //获取数字 1
@Value("#{'Spring Expression Language'}") //获取字符串常量
private String str;
@Value("#{dataSource.url}") //获取bean的属性
private String jdbcUrl;
@Autowired
private DataSourceTransactionManager transactionManager;
@RequestMapping("login")
public String login(String name,String password) throws FileNotFoundException{
System.out.println(number);
System.out.println(str);
System.out.println(jdbcUrl);
return "login";
}
}
@Value("normal")
private String normal; // 注入普通字符串
@Value("#{ systemProperties['os.name'] }")
private String systemPropertiesName; // 注入操作系统属性
@Value("#{ T(java.lang.Math).random() * 100.0 }")
private double randomNumber; //注入表达式结果
@Value("#{ beanInject.another }")
private String fromAnotherBean; // 注入其他Bean属性:注入beanInject对象的属性another,类具体定义见下面
@Value("classpath:com/hry/spring/configinject/config.txt")
private Resource resourceFile; // 注入文件资源
@Value("http://www.baidu.com")
private Resource testUrl; // 注入URL资源