Spring學(xué)習(xí)筆記

Spring配置元數(shù)據(jù)3種方式

  • 基于xml的配置文件

  • 基于注解的配置

    例如 通過 <context:component-scan base-package="com.company.">
    spring自動掃描帶有@Component锯厢、@Repository黎烈、@Service、@Controller標(biāo)簽的類自動注冊到spring容器.以及對標(biāo)記了@Required欢摄、@Autowired趣些、JSR250's @PostConstruct瓷耙、@PreDestroy太伊、@Resource剿另、JAX-WS's @WebServiceRef箫锤、EJB3's @EJB、JPA's @PersistenceContext雨女、@PersistenceUnit等注解的類進(jìn)行對應(yīng)的操作使注解生效(包含了annotation-config標(biāo)簽的作用)谚攒。

    getBean()的默認(rèn)名稱是類名(頭字母小寫),如果想自定義氛堕,可以@Service("aaaaa")這樣來指定馏臭。
    這種bean默認(rèn)是"singleton"的,如果想改變讼稚,可以使用@Scope("prototype")來改變,以及自定義初始化和銷毀方法等.

    @PostConstruct  
    public void init() {...}   
    @PreDestroy  
    public void destory() {...}   
    

    使用@Autowired自動注解接口的時(shí)候,如果該接口有多個(gè) 實(shí)現(xiàn),需要@Qualifier指定注入哪個(gè)實(shí)現(xiàn)類

  • 基于java的配置

@Autowired用法和流程

@Autowired, 可以用在以下三個(gè)地方

  • 屬性
    如果用在屬性上, 可以不用謝setter方法.
  • setter方法
    如果用在setter方法上,可以不用寫手動set,會自動注入
  • 構(gòu)造函數(shù)
    如果用在構(gòu)造函數(shù)上, 可以不用在xml文件中配置bean的 constructor-arg的參數(shù).
@Autowired是如何自動注入的??

首先根據(jù)配置文件的bean的id, 如果id找不到就找name, 繼續(xù)找不到就找類型,
即如下順序:

當(dāng)根據(jù)Type進(jìn)行自動注入時(shí), 如果有多個(gè)相同Type(比如一個(gè)接口有多個(gè)實(shí)現(xiàn)), 就需要@Qualifier這個(gè)注解了, Qualifier里面可以寫id或者name.

如果根據(jù)id或者name注入時(shí),參數(shù)/屬性的變量名必須和id/name完全一致.
比如:

private Hello hello;
 <bean id="hello" clas="com.company.HelloWorld"/>
 <bean id="hello2" clas="com.company.HelloChina"/>

bean的作用域

作用域 描述
singleton 該作用域?qū)?bean 的定義的限制在每一個(gè) Spring IoC 容器中的一個(gè)單一實(shí)例(默認(rèn))括儒。
prototype 該作用域?qū)我?bean 的定義限制在任意數(shù)量的對象實(shí)例。
request 該作用域?qū)?bean 的定義限制為 HTTP 請求锐想。只在 web-aware Spring ApplicationContext 的上下文中有效帮寻。
session 該作用域?qū)?bean 的定義限制為 HTTP 會話。 只在web-aware Spring ApplicationContext的上下文中有效赠摇。
global-session 該作用域?qū)?bean 的定義限制為全局 HTTP 會話固逗。只在 web-aware Spring ApplicationContext 的上下文中有效

當(dāng)使用scope="singleton"的時(shí)候,每次getbeean()調(diào)用的為同樣一個(gè)實(shí)例, 使用scope="prototype"時(shí),每次都是一個(gè)新的實(shí)例

初始化回調(diào)與銷毀回調(diào)

java實(shí)現(xiàn)

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.DisposableBean;
...
public class ExampleBean implements InitializingBean,
     DisposableBean{
    public void afterPropertiesSet() {
    // do some initialization work  
    }
    public void destroy() {
        // do some destruction work
    }
    ...
}

或者基于xml配置

<bean id="exampleBean"
    class="examples.ExampleBean"
    init-method="init"
    destroy-method="destroy"/>
...
public class ExampleBean {
    public void init() {
        // do some initialization work
    }
    public void destroy() {
        // do some destruction work
    }
}

建議不要使用 InitializingBean 或者 DisposableBean 的回調(diào)方法浅蚪,因?yàn)?XML 配置在命名方法上提供了極大
的靈活性

提供所有bean默認(rèn)的初始化和銷毀方法

如果你有太多具有相同名稱的初始化或者銷毀方法的 Bean,那么你不需要在每一個(gè) bean 上聲明 初始化方法和
銷毀方法烫罩【虮桑框架使用 元素中的 d default-init-method 和 d default-destroy-method 屬性提供了靈活地配置這種
情況,如下所示:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
    default-init-method="init"
    default-destroy-method="destroy">
    
    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>
</beans>

注入集合

list, set, map, prorps
<property name="list">
    <list>
        <ref bean="helloChina"/>
        <value>hello</value>
        <value>hi</value>
    </list>
</property>
<property name="map">
    <map>
        <entry key="1" value="INDIA"/>
        <entry key="2" value="USA"/>
    </map>
</property>
<property name="set">
    <set>
        <value>INDIA</value>
        <value>USA</value>
    </set>
</property>

p-namespace簡化xml配置

例子:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="john-classic" class="com.example.Person">
        <property name="name" value="John Doe"/>
        <property name="spouse" ref="jane"/>
    </bean>
    <bean name="jane" class="com.example.Person">
        <property name="name" value="John Doe"/>
    </bean>
</beans>
------------------
<?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:p="http://www.springframework.org/schema/p" <!--要添加這條配置-->
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
        
    <bean id="john-classic" class="com.example.Person"
        p:name="John Doe"
        p:spouse-ref="jane"/> <!-- -ref部分表明引用 -->
    </bean>
    <bean name="jane" class="com.example.Person"
        p:name="John Doe"/>
    </bean>
</beans>

Spring-AOP

aop命名空間標(biāo)簽
<?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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<!-- bean definition & AOP specific configuration -->
</beans>

配置依賴

<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.8.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.9</version>
</dependency>
聲明一個(gè)切入點(diǎn)
  • 基于xml配置
<aop:config>
    <aop:aspect id="myAspect" ref="aBean">
        <aop:pointcut id="businessService"
            expression="execution(* com.xyz.myapp.service.*.*(..))"/>
        <!-- a before advice definition -->
        <aop:before pointcut-ref="businessService" method="doRequiredTask"/>
        <!-- an after advice definition -->
        <aop:after pointcut-ref="businessService" method="doRequiredTask"/>
        
        <!-- an after-returning advice definition -->
        <!--The doRequiredTask method must have parameter named retVal -->
        <aop:after-returning pointcut-ref="businessService" returning="retVal" method="doRequiredTask"/>
        
        <!-- an after-throwing advice definition -->
        <!--The doRequiredTask method must have parameter named ex -->
        <aop:after-throwing pointcut-ref="businessService" throwing="ex" method="doRequiredTask"/>
        
        <!-- an around advice definition -->
        <aop:around pointcut-ref="businessService" method="doRequiredTask"/>
        ...
    </aop:aspect>
</aop:config>
<bean id="aBean" class="...">
...
</bean>

(..)表示方法可能有參數(shù).

  • 通過注解配置
    xml中添加<aop:aspectj-autoproxy/>
    配置實(shí)例:
@Aspect
public class AspectModule {
    @Pointcut("execution(* com.hand.aop.Hello.test())")
    private void testService(){}
    @Before("testService()")
    public void doBeforeTask() {
        System.out.println("before task");
    }
    @After("testService()")
    public void doAfterTask(){
        System.out.println("after task");
    }
    @AfterReturning(pointcut = "testService()", returning="retVal")
    public void doAfterReturnningTask(Object retVal){
        System.out.println("doAfterReturnningTask");
    }
    @AfterThrowing(pointcut = "testService()", throwing="ex")
    public void doAfterThrowingTask(Exception ex){
        System.out.println("doAfterThrowingTask");
    }
    @Around("testService()")
    public void doAroundTask() {
        System.out.println("doAroundTask");
    }
}
---
<bean id="aspectModule" class="com.company.AspectModule"/>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末嗡髓,一起剝皮案震驚了整個(gè)濱河市操漠,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌饿这,老刑警劉巖浊伙,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異长捧,居然都是意外死亡嚣鄙,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進(jìn)店門串结,熙熙樓的掌柜王于貴愁眉苦臉地迎上來哑子,“玉大人,你說我怎么就攤上這事肌割∥则眩” “怎么了?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵把敞,是天一觀的道長弥奸。 經(jīng)常有香客問我,道長奋早,這世上最難降的妖魔是什么盛霎? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮耽装,結(jié)果婚禮上愤炸,老公的妹妹穿的比我還像新娘。我一直安慰自己掉奄,他們只是感情好规个,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著挥萌,像睡著了一般绰姻。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上引瀑,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天狂芋,我揣著相機(jī)與錄音,去河邊找鬼憨栽。 笑死帜矾,一個(gè)胖子當(dāng)著我的面吹牛翼虫,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播屡萤,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼珍剑,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了死陆?” 一聲冷哼從身側(cè)響起招拙,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎措译,沒想到半個(gè)月后别凤,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡领虹,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年规哪,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片塌衰。...
    茶點(diǎn)故事閱讀 40,852評論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡诉稍,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出最疆,到底是詐尸還是另有隱情杯巨,我是刑警寧澤,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布肚菠,位于F島的核電站舔箭,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏蚊逢。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一箫章、第九天 我趴在偏房一處隱蔽的房頂上張望烙荷。 院中可真熱鬧,春花似錦檬寂、人聲如沸终抽。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽昼伴。三九已至,卻和暖如春镣屹,著一層夾襖步出監(jiān)牢的瞬間圃郊,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工女蜈, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留持舆,地道東北人色瘩。 一個(gè)月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像逸寓,于是被迫代替她去往敵國和親居兆。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,851評論 2 361

推薦閱讀更多精彩內(nèi)容