Spring之旅第四篇-註解配置詳解

1、引言

上一篇Spring的配置文章評論中有朋友指出如今不多用xml類配置SpringBean了,都是用註解的方式來進行配置,那麼這篇就來說註解配置。spring

使用.xml文件來對bean進行注入的缺點很明顯:文件會十分龐大,若是分多模塊去配置,文件又特別的多,這些會致使可讀性和可維護性變差。app

爲了解決這兩個問題,Spring引入了註解,經過"@XXX"的方式,讓註解與Java Bean緊密結合,既大大減小了配置文件的體積,又增長了Java Bean的可讀性與內聚性。異步

2、將對象註冊到容器

註解如何使用呢,分爲三步ide

第一步:在 applicationContext.xml 中引入命名空間測試

第二步:在 applicationContext.xml 文件中引入註解掃描器this

<context:component-scan base-package="com.yuanqinnan.test" ></context:component-scan>

base-package:表示含有註解類的包名spa

若是掃描多個包,則上面的代碼書寫多行,改變 base-package 裏面的內容便可!.net

若是使用Idea引入註解掃描器,就會直接引入命名空間component

第三步:在 Car 類中添加註解@Componentxml

@Component
public class Car {

    private String Color;

    public String getColor() {
        return Color;
    }

    public void setColor(String color) {
        Color = color;
    }

    @Override
    public String toString() {
        return "Car{" +
                "Color='" + Color + '\'' +
                '}';
    }
}

第四步:測試

ApplicationContext ctx=new ClassPathXmlApplicationContext("META-INF/applicationContext.xml");
          //獲取bean的實例
          Car car=(Car) ctx.getBean("car");
          System.out.println(car.toString());

結果:Car{Color='null'}

3、值類型注入

@Value("yellow")
public void setColor(String color) {
    Color = color;
}

結果:Car{Color='yellow'}

4、引用類型注入

引用類型分爲自動裝配@Autowired和手動注入@Resource

4.1 @Autowired

顧名思義,就是自動裝配,其做用是爲了消除代碼Java代碼裏面的getter/setter與bean屬性中的property。固然,getter看我的需求,若是私有屬性須要對外提供的話,應當予以保留。

@Autowired默認按類型匹配的方式,在容器查找匹配的Bean,當有且僅有一個匹配的Bean時,Spring將其注入@Autowired標註的變量中。

建立一個新類Boss

@Component
public class Boss {
    //自動裝配
    @Autowired
    private Car car;

    private String name;
    @Value("袁帥")
    public void setName(String name) {
        this.name = name;
    }

    public String getName() {

        return name;
    }

    @Override
    public String toString() {
        return "Boss{" +
                "car=" + car.getColor() +
                ", name='" + name + '\'' +
                '}';
    }
}

測試:

Boss boss=(Boss)ctx.getBean("boss");
System.out.println(boss.toString());

結果:Boss{car=yellow, name='袁帥'}

這種方式存在匹配到多個類型一致的的狀況,這種狀況須要Qualifier來解決

定義一個Car接口:

public interface ICar {
     String getCarName();
}

兩個實現類BMWCar和BenzCar:

@Component("benzCar")
public class BenzCar implements ICar {

    @Override
    public String getCarName() {
        return "奔馳";
    }
}
@Component("bmwCar")
public class BMWCar implements ICar {
    @Override
    public String getCarName() {
        return "寶馬";
    }
}

工廠類:

@Component("cf")
public class CarFactory {
    @Autowired
    private ICar iCar;

    public String toString(){
        return iCar.getCarName();
    }
}

很明顯這種寫法會報錯,

No unique bean of type [com.spring.service.ICar] is defined: expected single matching bean but found 2: [bmwCar, benz]

很明顯這種寫法會報錯,由於Spring並不知道應當引用哪一個實現類,這個時候使用@Qualifie

@Autowired
@Qualifier("bmwCar")
private ICar iCar;

結果:寶馬

4.2 @Resource

@Resource註解與@Autowired註解做用很是類似,這個就簡單說了,看例子:

@Resource(type = BenzCar.class)
private ICar iCar2;

@Resource(name = "benzCar")
private ICar iCar3;

5、經常使用註解總結

最後介紹經常使用的註解

@Configuration把一個類做爲一個IoC容器,它的某個方法頭上若是註冊了

@Bean,就會做爲這個Spring容器中的Bean。

@Scope註解 做用域 @Lazy(true) 表示延遲初始化

@Service用於標註業務層組件、

@Controller用於標註控制層組件(如struts中的action)

@Repository用於標註數據訪問組件,即DAO組件。

@Component泛指組件,當組件很差歸類的時候,咱們可使用這個註解進行標註。

@Scope用於指定scope做用域的(用在類上)

@PostConstruct用於指定初始化方法(用在方法上)

@PreDestory用於指定銷燬方法(用在方法上)

@DependsOn:定義Bean初始化及銷燬時的順序

@Primary:自動裝配時當出現多個Bean候選者時,被註解爲@Primary的Bean將做爲首選者,不然將拋出異常 @Autowired 默認按類型裝配,若是咱們想使用按名稱裝配,能夠結合@Qualifier註解一塊兒使用。以下: @Autowired @Qualifier("personDaoBean") 存在多個實例配合使用 @Resource默認按名稱裝配,當找不到與名稱匹配的bean纔會按類型裝配。

@PostConstruct 初始化註解

@PreDestroy 摧毀註解 默認 單例 啓動就加載

@Async異步方法調用

相關文章
相關標籤/搜索