Spring實戰(zhàn)之Qualifier注解用法示例
更新時間:2019年12月27日 09:37:47 作者:cakincqm
這篇文章主要介紹了Spring實戰(zhàn)之Qualifier注解用法,結合實例形式詳細分析了spring Qualifier注解相關配置、定義與使用方法,需要的朋友可以參考下
本文實例講述了Spring實戰(zhàn)之Qualifier注解用法。分享給大家供大家參考,具體如下:
一 配置
<?xml version="1.0" encoding="GBK"?> <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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <context:component-scan base-package="org.crazyit.app.service"/> </beans>
二 接口
Axe
package org.crazyit.app.service; public interface Axe { public String chop(); }
Person
package org.crazyit.app.service; public interface Person { public void useAxe(); }
三 Bean
Chinese
package org.crazyit.app.service.impl; import org.springframework.stereotype.*; import org.springframework.beans.factory.annotation.*; import org.crazyit.app.service.*; @Component public class Chinese implements Person { @Autowired @Qualifier("steelAxe") private Axe axe; // // axe的setter方法 // @Autowired // public void setAxe(@Qualifier("stoneAxe") Axe axe) // { // this.axe = axe; // } // 實現(xiàn)Person接口的useAxe()方法 public void useAxe() { // 調用axe的chop()方法, // 表明Person對象依賴于axe對象 System.out.println(axe.chop()); } }
SteelAxe
package org.crazyit.app.service.impl; import org.springframework.stereotype.*; import org.crazyit.app.service.*; @Component public class SteelAxe implements Axe { public String chop() { return "鋼斧砍柴真快"; } }
StoneAxe
package org.crazyit.app.service.impl; import org.springframework.stereotype.*; import org.crazyit.app.service.*; @Component public class StoneAxe implements Axe { public String chop() { return "石斧砍柴好慢"; } }
四 測試類
package lee; import org.springframework.context.*; import org.springframework.context.support.*; import org.crazyit.app.service.*; public class BeanTest { public static void main(String[] args) { // 創(chuàng)建Spring容器 AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // 注冊關閉鉤子 ctx.registerShutdownHook(); Person person = ctx.getBean("chinese" , Person.class); person.useAxe(); } }
五 測試結果
鋼斧砍柴真快
更多關于java相關內容感興趣的讀者可查看本站專題:《Spring框架入門與進階教程》、《Java數(shù)據結構與算法教程》、《Java操作DOM節(jié)點技巧總結》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。
相關文章
springboot項目獲取resources相對路徑的方法
這篇文章主要介紹了springboot項目獲取resources相對路徑的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12mall整合SpringSecurity及JWT認證授權實戰(zhàn)下
這篇文章主要為大家介紹了mall整合SpringSecurity及JWT認證授權實戰(zhàn)第二篇,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06