Python 官方文档:入门教程 => 点击学习
一、@Value注解 在Person的属性上使用@Value注解指定注入值 public class Person { @Value("#{20-2}")
在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({"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注解驱动开发内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: 详解Spring注解驱动开发之属性赋值
本文链接: https://www.lsjlt.com/news/126898.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0