详解Spring注解驱动开发之属性赋值

一、@Value注解

Person的属性上使用@Value注解指定注入值

public class Person {        @Value("#{20-2}")     //SpEL表达式 #{}    private Integer id;        @Value("张三")        //基本数据类型    private String name;}

配置类

@Configurationpublic 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"})@Configurationpublic 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注解驱动开发内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

人情似纸张张薄,世事如棋局局新。

详解Spring注解驱动开发之属性赋值

相关文章:

你感兴趣的文章:

标签云: