SpringFramework|@Primary

@Primary的使用

前述

Java: 1.8java

Maven: 3spring

SpringFramework版本以及各組件成員: 5.1.1.RELEASEthis

  • spring-context
  • spring-core
  • spring-beans

@Primary表示當多個bean能夠自動裝配到單值依賴項時,應該優先選擇特定的bean。若是候選者中只存在一個主bean,則它將成爲自動裝配的值。code

示例

電影的Bean類: Movie. 將會有兩個MovieBean, 而咱們須要播放第一場電影 - 動做片. 接下來纔是喜劇片.component

電影Bean - Movie.java

package yag;

import org.springframework.context.annotation.Configuration;

@Configuration
public class Movie {

    private String content;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Movie(){

    }
}

播放者(BeanUser) - MovieShower.java

package yag;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MovieShower {

    private Movie movie;

    // 注入Movie實例
    @Autowired
    public void setMovie(Movie movie) {
        this.movie = movie;
    }

    // 使用實例
    public void show(){
        // 播放影片內容
        System.out.println(movie.getContent());
    }
}

Java配置 - MovieConfig.java

package yag;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class MovieConfig {

    @Bean
    @Primary
    public Movie firstMovie(){
        // 用了這個方法來替代XML配置中的value屬性以賦固定值.
        Movie movie = new Movie();
        movie.setContent("正在播放動做片");
        return movie;
    }

    @Bean
    public Movie secondMovie(){
        Movie movie = new Movie();
        movie.setContent("正在播放喜劇電影");
        return new Movie();
    }

    // BeanUser
    @Bean
    public MovieShower movieShower(){
        return new MovieShower();
    }
}

啓用註解掃描 - spring-beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="yag"/>
</beans>

執行者

package yag;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Runner {

    public static void main(String[] args){
        ApplicationContext c = new AnnotationConfigApplicationContext(MovieConfig.class);
        MovieShower shower = c.getBean(MovieShower.class);
        shower.show();
    }
}

運行結果

正在播放動做片

Process finished with exit code 0
相關文章
相關標籤/搜索