Spring源碼窺探之:@Value


1. 首先定義實體

/**
 * @author 70KG
 * @Title: Apple
 * @Description: 蘋果實體
 * @date 2018/10/22下午9:26
 * @From www.nmyswls.com
 */
@Data
public class Apple {

    @Value("${apple.color}")
    private String color;

    @Value("紅富士")
    private String name;

}

2. 屬性文件test.properties放在resource下

apple.color=red

3. spring的配置類

@PropertySource(value = "classpath:/test.properties")將屬性文件讀取到內存中

/**
 * @author 70KG
 * @Title: AppleConfig
 * @Description: 配置類
 * @date 2018/10/22下午9:28
 * @From www.nmyswls.com
 */
@Configuration
@PropertySource(value = "classpath:/test.properties")
public class AppleConfig {

    @Bean
    public Apple apple() {
        return new Apple();
    }

}

4. 測試

/**
 * @author 70KG
 * @Title: Test01
 * @Description: test
 * @date 2018/10/22下午9:30
 * @From www.nmyswls.com
 */
public class Test01 {

    @Test
    public void test01() {
        AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(AppleConfig.class);
        // 從容器中獲取所有的bean
        String[] names = app.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println("bean的名字--->" + name);
        }
        Apple apple = (Apple) app.getBean("apple");
        System.out.println(apple);

        System.out.println("==========IOC容器創建完成==========");

        ConfigurableEnvironment environment = app.getEnvironment();
        String property = environment.getProperty("apple.color");
        System.out.println("獲取配置文件中的屬性---->" + property);
    }

}

5. 測試結果

bean的名字--->org.springframework.context.annotation.internalConfigurationAnnotationProcessor
bean的名字--->org.springframework.context.annotation.internalAutowiredAnnotationProcessor
bean的名字--->org.springframework.context.annotation.internalRequiredAnnotationProcessor
bean的名字--->org.springframework.context.annotation.internalCommonAnnotationProcessor
bean的名字--->org.springframework.context.event.internalEventListenerProcessor
bean的名字--->org.springframework.context.event.internalEventListenerFactory
bean的名字--->appleConfig
bean的名字--->apple
Apple(color=red, name=紅富士)
==========IOC容器創建完成==========
獲取配置文件中的屬性---->red

前面的都是bean的后置處理器


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM