使用spring注解——定義bean和自動注入


對於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!";
    }
}
View Code

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();
    }
}
View Code

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>
View Code

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() );        
    }
}
View Code

5、運行測試類,可以看到輸出。說明注解成功定義bean,並成功完成注入

信息: Loading XML bean definitions from class path resource [bean.xml]
Dinglei has a 55.8 kg black pig!

參考: 

謝謝無私分享的伙伴,寫的非常詳細的一篇:Spring注解詳解


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM