Spring注解07 @Value 赋值 @PropertySource 加载外部配置文件

  • @Value 赋值

  • @PropertySource 加载外部配置文件

  • 配置文件

@PropertySource("classpath:/person.properties")
@Configuration
@ComponentScan(value = "com.tommy.bean")
public class ValueConfig {
}

person.properties

person.nickName=TommyDog

bean类

@Data
@Component
public class Person {
    @Value("jm")
    private String name;
    @Value("#{30-12}")
    private int age;
    @Value("${person.nickName}")
    private String nickName;
    public Person(String name, int age, String nickName) {
        this.name = name;
        this.age = age;
        this.nickName = nickName;
    }
    public Person() {
    }
}

测试类

public class IOCValueTest {
    @Test
    public void testImport(){
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValueConfig.class);
        printDefineName(applicationContext);
        System.out.println("============================");
        final Person person = (Person) applicationContext.getBean("person");
        System.out.println("person to string1 : "+person.toString() );
        final Person bean = applicationContext.getBean(Person.class);
        System.out.println("person to string2 : "+bean.toString() );

    }
    private void printDefineName(ApplicationContext applicationContext) {
        final String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        for (String name :beanDefinitionNames) {
            System.out.println("name: "+name);
        }
    }
}

测试结果:

name: org.springframework.context.annotation.internalConfigurationAnnotationProcessor
name: org.springframework.context.annotation.internalAutowiredAnnotationProcessor
name: org.springframework.context.annotation.internalCommonAnnotationProcessor
name: org.springframework.context.event.internalEventListenerProcessor
name: org.springframework.context.event.internalEventListenerFactory
name: valueConfig
name: dog
name: fish
name: myBeanPostProcessor
name: person
============================
person to string1 : Person(name=jm, age=18, nickName=TommyDog)
person to string2 : Person(name=jm, age=18, nickName=TommyDog)

Process finished with exit code 0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容