Bootstrap

基础7:注解详解(属性赋值)

@Value赋值

有下面几个点需要留意下:

①不同于XML文件配置时必须带有setter方法,在使用@Value注解时,setter方法不是必须的;

②@Value注解支持:字面量、SpEL表达式、读取Properties文件;

③当读取Properties文件时,需要在@Configuration注解的类里面,通过@PropertySources或者@PropertySource注解来引入properties文件,当引入properties文件后,Spring就会把properties里面的内容放到ConfigurableEnvironment中,@Value说白了,在读取properties时,其实是从ConfigurableEnvironment中读取的;

@Component

public class OrgDao {

 

    // 基本字面量

    @Value("中国华夏银行")

    private String orgName;

 

    // SpEL表达式

    @Value("#{100+50}")

    private int peopleCount;

 

    // 获取properties文件属性值

    @Value("${address}")

    private String address;

 

 

    @Override

    public String toString() {

        return "OrgDao{" +

                "orgName='" + orgName + '\'' +

                ", peopleCount=" + peopleCount +

                ", address='" + address + '\'' +

                '}';

    }

}

 

@PropertySources(

{@PropertySource(value = {"classpath:/org.properties"})}

)

@Import(ImportTest.class)

@Configuration

@ComponentScan(

        value = "com.spring.annotation",

        excludeFilters = {

                @ComponentScan.Filter(

                        type = FilterType.ANNOTATION,

                        classes = {Controller.class, Service.class})

        })

public class MainConfig {

 

    /**

     * @Bean,类型为返回值的类型,id默认是方法名(大小写与方法名完全一致)

     * */

    @Bean

    @Lazy

    @Conditional(MyConditional.class)

    public Persion persion(){

        return new Persion("ZhangSan",30);

    }

}

 

@Test

    public void testOrg(){

        ConfigurableEnvironment environment = applicationContext.getEnvironment();

        System.out.println(environment.getProperty("address"));

        OrgDao orgDao = (OrgDao) applicationContext.getBean("orgDao");

        System.out.println(orgDao.toString());

    }

;