一、@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);
    }

输出结果:

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

二、@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;
}

输出结果:

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

因为配置文件中的值默认都加载到环境变量中,所有还可以通过环境变量来获取配置文件中的值

 @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注解驱动开发之属性赋值

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。