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

你可能感兴趣的:(Spring注解07 @Value 赋值 @PropertySource 加载外部配置文件)