详解Spring注解驱动开发之属性赋值
更新时间:2021年05月26日 16:38:18 作者:煎丶包
今天带大家学习Spring注解驱动开发的相关知识,文中有非常详细的代码示例,对正在学习Java的小伙伴们很有帮助,需要的朋友可以参考下
一、@Value注解
在Person的属性上使用@Value注解指定注入值
public class Person {
@Value("#{20-2}") //SpEL表达式 #{}
private Integer id;
@Value("张三") //基本数据类型
private String name;
}
配置类
@Configuration
public class MainConfigOfPropertyValues {
@Bean
public Person person(){
return new Person();
}
}
测试
@Test
public void testValues(){
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
String[] beanDefinitionNames = context.getBeanDefinitionNames();
for (String beanName : beanDefinitionNames){
System.out.println(beanName);
}
Person person = (Person) context.getBean("person");
System.out.println(person);
}
输出结果:

二、@PropertySource加载外部配置文件
配置类加上@PropertySource注解,引入外部配置文件
@PropertySource({"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {
@Bean
public Person person(){
return new Person();
}
}
使用${属性值}注入属性值
public class Person {
@Value("#{20-2}") //SpEL表达式 #{}
private Integer id;
@Value("张三") //基本数据类型
private String name;
@Value("${person.age}") //使用外部配置文件注入属性值
private Integer age;
}
输出结果:

因为配置文件中的值默认都加载到环境变量中,所有还可以通过环境变量来获取配置文件中的值
@Test
public void testValues(){
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
String[] beanDefinitionNames = context.getBeanDefinitionNames();
for (String beanName : beanDefinitionNames){
System.out.println(beanName);
}
Person person = (Person) context.getBean("person");
System.out.println(person);
Environment environment = context.getEnvironment();
String age = environment.getProperty("person.age");
System.out.println("age = " + age);
}
输出结果:

到此这篇关于详解Spring注解驱动开发实现属性赋值的文章就介绍到这了,更多相关Spring注解驱动开发内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
MyBatis使用resultMap如何解决列名和属性名不一致
这篇文章主要介绍了MyBatis使用resultMap如何解决列名和属性名不一致的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-01-01
Spring中@RabbitHandler和@RabbitListener的区别详析
@RabbitHandler是用于处理消息的方法注解,它与@RabbitListener注解一起使用,这篇文章主要给大家介绍了关于Spring中@RabbitHandler和@RabbitListener区别的相关资料,需要的朋友可以参考下2024-02-02
Mybatis-Plus中使用@DS注解动态选择数据源的源码解读
这篇文章主要介绍了Mybatis-Plus中使用@DS注解动态选择数据源的源码解读,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2023-07-07


最新评论