1.使用@Value给属性字段赋值
- 直接赋值基本数据
- 可以写SpEL ,#{}
- 可以写${},取出配置文件(properties文件)中的值(在运行变量中的值) 和之前在xml配置相似
1.1 前两种的使用例子:
对象类:
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class User {
@Value("Vison") //基本使用数据,包含各种基本数据的使用
private String name;
@Value("#{56-32}") //spring的EL表达式
private Integer age;
}
配置类,只配置了无参构造
@Configuration
public class MainPropertyConfig {
@Bean
public User user(){
return new User();
}
}
测试类:
public class MainTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainPropertyConfig.class);
Object user = applicationContext.getBean("user");
System.out.println(user);
}
}
结果显示的就是:
User(name=Vison, age=24)
1.2 ${} ,导入配置文件需要加@PropertySource来导入配置文件
1)新建一个config.properties放在resource文件下
code=vison
2)配置类,使用@PropertySource导入配置文件,使用@Value("${code})来赋值
@PropertySource(value={"classpath:/config.properties"}) //这里可以使用多个配置文件 ,“/”表示根目录下
@Configuration
public class MainPropertyConfig {
@Value("${code}")
private String code;
@Bean
public User user(){
System.out.println(code); //这里打印属性内容
return new User();
}
}
3)测试,结果会打印出来vison值