1. 程式人生 > >【Spring】【一】基本註解以及小例項

【Spring】【一】基本註解以及小例項

基本註解: 1.標註 bean類  ———————————————————— @Component:標準一個普通的spring Bean類。 @Controller:標註一個控制器元件類。 @Service:標註一個業務邏輯元件類。 @Repository:標註一個DAO元件類。 ————————————————————
2. 作用域 ————————————————————
@Scope :prototype、request、session、global session
————————————————————
3.自動裝配 ————————————————————
 @Autowired

————————————————————
@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非同步方法呼叫
______________________________________________________________________ bean.xml 搜尋 某個包下的所有類
 <context:component-scan base-package="com.kn.beanScope" />

______________________________________________________________________ OH.java 注意@Component 註解,即 標註一個普通的bean 
package com.kn.beanScope;

import org.springframework.stereotype.Component;

@Component
public class OH {
    public void sout(){
        System.out.println("???? THIS IS OH date!");
    }
}

BeanScope.java @Scope 設定作用域 為 每次新建自身例項
package com.kn.beanScope;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

@Component
@Scope("prototype")
public class BeanScope {
    @Autowired
    private OH oh;
    private String beanname;
    public void say(){
        System.out.println("BeanScope say :"+this.hashCode()+"from "+beanname);
        oh.sout();
    }
    public  void init(){
        beanname="FFF";
    }
    public  void destroy(){
        beanname="GGGG";
        say();
    }


}
測試類: UserAxeTest.java
        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean_Zj.xml");

        BeanScope beanScope=ctx.getBean("beanScope",BeanScope.class);
        beanScope.init();
        beanScope.say();
        BeanScope beanScope1=ctx.getBean("beanScope",BeanScope.class);
        beanScope1.say();
獲取兩次 beanScope 然後 第一次先呼叫init 再say,第二次 直接say 結果:
BeanScope say :1873859565from FFF
???? THIS IS OH date!
BeanScope say :1843289228from null
???? THIS IS OH date! 可以看出,是兩個不同的例項。 第一次成功初始化,from FFF 第二次則為null。