美文网首页
Spring注解之三组件赋值

Spring注解之三组件赋值

作者: Java及SpringBoot | 来源:发表于2019-11-27 11:02 被阅读0次

个人专题目录


1.3. 组件赋值

@Value赋值&@PropertySource(s)加载外部配置文件

public class Person {

    //使用@Value赋值;
    //1、基本数值
    //2、可以写SpEL; #{}
    //3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值)

    @Value("张三")
    private String name;
    @Value("#{20-2}")
    private Integer age;

    @Value("${person.nickName}")
    private String nickName;

    public Person(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }

    public Person() {
        super();
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", nickName=" + nickName + "]";
    }

}
//使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用${}取出配置文件的值
@PropertySource(value = {"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {

    @Bean
    public Person person() {
        return new Person();
    }

}
public class IOCTest_PropertyValue {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
    @Test
    public void test01(){
        printBeans(applicationContext);
        System.out.println("=============");
        
        Person person = (Person) applicationContext.getBean("person");
        System.out.println(person);
        
        
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        String property = environment.getProperty("person.nickName");
        System.out.println(property);
        applicationContext.close();
    }
    
    private void printBeans(AnnotationConfigApplicationContext applicationContext){
        String[] definitionNames = applicationContext.getBeanDefinitionNames();
        for (String name : definitionNames) {
            System.out.println(name);
        }
    }
}

相关文章

网友评论

      本文标题:Spring注解之三组件赋值

      本文链接:https://www.haomeiwen.com/subject/xjpywctx.html