對於java bean的定義和依賴配置,使用xml文件真心是不方便。
今天學習如何用注解,解決bean的定義和注入。
常用注解:
1、自動注入:@Resources,@Autowired
2、Bean定義:@Component、@Repository、@Service 和 @Constroller
@Component是個泛化概念,可以用在任何層次。如果是web開發,盡量用@Repository、@Service 和 @Constroller
Demo:
以丁磊養豬為例,Pig和DingLei兩個類
1、Pig類,以@Component定義為bean

@Component public class Pig { private Double weight; private String color; public Pig(){ this.weight = 55.8; this.color = "black"; } public Double getWeight() { return weight; } public void setWeight(Double weight) { this.weight = weight; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String toString(){ return weight + " kg " + color + " pig!"; } }
2、DingLei類,以@Component定義為bean,同時用@Autowired注入依賴pig

@Component public class DingLei { @Autowired private Pig pig; public Pig getPig() { return pig; } public void setPig(Pig pig) { this.pig = pig; } public String toString(){ return "Dinglei has a " + pig.toString(); } }
3、bean.xml文件中,配置包掃描,注解才生效
<context:annotation-config/> :啟用注釋驅動自動注入
<context:component-scan/>:對類包進行掃描以實施注釋驅動 Bean 定義,同時隱式啟用注釋驅動自動注入。因此,配置這個就可以

<?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-3.0.xsd"> <!-- <context:annotation-config/> --> <context:component-scan base-package="anotation"/> </beans>
4、測試類

public class TestAnotation { @SuppressWarnings("resource") public static void main(String[] arg) { ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); DingLei dingLei = (DingLei) context.getBean("dingLei"); System.out.println( dingLei.toString() ); } }
5、運行測試類,可以看到輸出。說明注解成功定義bean,並成功完成注入
信息: Loading XML bean definitions from class path resource [bean.xml] Dinglei has a 55.8 kg black pig!
參考:
謝謝無私分享的伙伴,寫的非常詳細的一篇:Spring注解詳解