1. 程式人生 > >spring屬性賦值和自動裝配

spring屬性賦值和自動裝配

一  @Value賦值和@propertySource載入外部配置檔案

1、@Value 一般用在屬性和setter方法上,當該類註冊成bean時,會自動為其屬性或方法的引數賦值。注意:一定不能用在靜態方法上,否則會失效

2、用法:

  @Value("placeholder")    //賦予指定值

  @Value("${placeholder}")  //賦予配置檔案中指定key為placeholder的值

3、@PropertySource("classpath:application.properties")  //匯入指定的配置檔案,一般寫在主配置類上

4、示例:

 

public class Desk{
    
    private String name;
    
    @Value("1")
    private int hight;
    
    private String owner;
    

    public  Desk() {
        
    }
    
    public  Desk(String name) {
        this.name = name;
    }

    public String getName() {
        return
name; } @Value("${name}") public void setName(String name) {this.name = name; } public int getHight() { return hight; } public void setHight(int hight) { this.hight = hight; } public String getOwner() { return owner; } @Value(
"${owner}") public void setOwner(String owner) { this.owner = owner; } }

 

5、建立bean示例:

@PropertySource({"classpath:application.properties"})
@Configuration
@ComponentScan(value="com.dj")
public class MainConfig {
    
    @Bean
    public Desk getDesk() {
        return new Desk();
    }
}

 

二 @Autowired和@Qualifier和@Primary

1、@Autowired(required=boolean)  // 預設byType注入,如果找到多個相同型別的元件,再將屬性的名稱byName去注入,required設定是否必須注入,預設true,可用於屬性、方法、構造器、引數

2、@Qualifier("name")  //與@Autowired搭配使用讓@Autowired變成byName去注入

3、@Primary  //當多個bean是同一個型別時,@Autowired會首選@Primary 的bean去裝配

 

三  @Resource和@Inject

1、@Resource(name="name") //可以和@Autowired一樣實現自動注入功能,預設byName進行裝配;但不能支援 @Primary 和 @Autowired(required=false)

2、@Inject //需要匯入javax.inject包才有這個註解,和@Autowired功能一樣,但是沒有 @Autowired(required=false) 功能

3、一般spring自動注入推薦@Autowired注入

 

四、Aware注入,spring底層注入原理:

1、實現了Aware家族介面的bean可以獲取到當前bean的一些屬性,比如:

  ApplicationContextAware  //獲取到當前bean的ApplicationContext

  BeanNameAware  //獲取到當前bean的name

  EmbeddedValueResolverAware  //獲取到@Value的解析器

  。。。

利用這種方法也能對bean進行屬性賦值,注入

2、示例:

@Component
public class User implements ApplicationContextAware,BeanNameAware,EmbeddedValueResolverAware{
    
    private String name;
    
    private Dog myDog;
    
    private int age;
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Dog getMyDog() {
        return myDog;
    }

    public void setMyDog(Dog myDog) {
        this.myDog = myDog;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        
        System.out.println("傳入的ioc:"+applicationContext);
        this.myDog = applicationContext.getBean(Dog.class);
    }
    
    @Override
    public void setBeanName(String name) {
        this.name = name;
        System.out.println("beanName="+name);
    }

    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        
        this.age = Integer.parseInt(resolver.resolveStringValue("#{20-10}"));
        System.out.println(this.age);
    }

}

3、建立測試類

    public static void main(String[] args) {
        ApplicationContext application = new AnnotationConfigApplicationContext(MainConfig.class);
        User user = application.getBean(User.class);
        System.out.println(JSON.toJSONString(user));
    }

這樣就能打印出建立的bean

4、原理:每一個Aware都有一個對應的Processor來處理他,xxxAware 對應 xxxProcessor

 

四、@Profile環境搭建

1、@Profile("profileName")  //spring在啟動時,標註了@Profile的bean如果其profileName與啟動時設定的profileName不一樣,那麼就不會註冊該bean,@Profile預設為@Profile("default"),沒有標註@Profile的bean任何時候都會被載入

2、設定命令列引數選擇 profileName:

  選擇 Run As --> Run Configurations --> Arguments,在VM Arguments框中輸入:Dspring.profiles.active=profileName ,選擇 Apply-->Run 即可指定執行環境

3、使用無參的 AnnotationConfigApplicationContext 自定義 spring 的啟動方式來選擇 profileName:

  示例:

    public static void main(String[] args) {
        //1.啟動一個無參的applicationContext
        AnnotationConfigApplicationContext application = new AnnotationConfigApplicationContext();
        //2.設定的applicationContext的執行環境
        application.getEnvironment().setActiveProfiles("test");
        //3.註冊主配置類
        application.register(MainConfig.class);
        //4.啟動重新整理容器
        application.refresh();
    }

這樣也可以選擇執行時環境。