spring學習12( 注解 配置 bean關系)

通過使用@Autowired注解來配置bean之間的關系

  • @Autowired (Spring原理是后置處理器)會根據修飾的 構造器 屬性 方法參數的類型自動裝配

  • @Autowired所修飾的bean 必須加入spring 但可以使用@Autowired(required=false)設置可以為null

  • @Autowired 修飾的bean的類型有多個時 默認@Autowired比對bean的名字 名字不匹配會報錯

  • 如果關聯的bean沒有指定名字可以使用 @Qualifier(類的name)指定類的name
package note;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

@org.springframework.stereotype.Controller("controller")
public class Controller {
    //@Autowired (Spring原理是后置處理器)會根據修飾的 構造器 屬性 方法參數的類型自動裝配
    //@Autowired所修飾的bean 必須加入spring 但可以使用@Autowired(required=false)設置可以為空
    //@Autowired 修飾的bean的類型有多個時  默認@Autowired比對bean的名字 名字不匹配會報錯
    //如果關聯的bean沒有指定名字可以使用 @Qualifier(類的name)指定類的name
    
    @Autowired(required=false)
    @Qualifier("service")
    private Service service;
    
    public void execute() {
        System.out.println("Controller 執行");
        service.add();
    }

    public Service getService() {
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }
    
}

package note;

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

@org.springframework.stereotype.Service
public class Service {
    @Autowired
    private Repository repository;
    
    public void add() {
        System.out.println("Service add");
        repository.save();
    }

    public Repository getRepository() {
        return repository;
    }

    public void setRepository(Repository repository) {
        this.repository = repository;
    }

}


package note;
@org.springframework.stereotype.Repository("repository")
public class Repository {
    
    public void save() {
        System.out.println("Repository 保存");
    }

}

配置:

    <context:component-scan base-package="note"></context:component-scan>

使用

    /**
     * 注解 配置 bean關系
     */
    public static void testScanBean() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("scanb.xml");
        Controller controller=ctx.getBean("controller",Controller.class);
        controller.execute();
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容