這篇文章給大家分享的是有關Spring注解驅動開發之屬性賦值的示例分析的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
在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注解驅動開發之屬性賦值的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。