1. 程式人生 > >Spring中的初始化註解@PostConstruct

Spring中的初始化註解@PostConstruct

配置檔案:

<?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"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:lang="http://www.springframework.org/schema/lang" xmlns:oxm="http://www.springframework.org/schema/oxm"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.2.xsd
        http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- spring的註解 -->
<!-- <context:annotation-config/> -->
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<bean id="person" class="aop.Person">
<property name="message" value="123"></property>
</bean>
<!-- 切點 -->
<bean id="log" class="aop.Log"/>
<!-- 切點通知,前置通知,後置通知,success通,環繞通知 .配置各種通知-->
<!-- <aop:config>
<aop:aspect ref="log">
宣告切入點,方法名。第一個*返回的引數,第二個*任意的類名名,第三個引數*是任意的,括號裡面的時任意的引數
<aop:pointcut expression="execution(* aop.*.*(..))" id="oprater"/>
配置切點
<aop:before method="before" pointcut-ref="oprater"/>
<aop:after-returning method="success" pointcut-ref="oprater"/>
<aop:after method="after" pointcut-ref="oprater"/>
<aop:around method="around" pointcut-ref="oprater"/>
</aop:aspect>
</aop:config> -->
<!-- 建立bean -->
<bean id="ope" class="aop.Operate"></bean>
<bean id="aop" class="aop.Aop"></bean>
</beans>

配置檔案中的註冊:

<context:annotation-config>與

<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>作用是一樣的

實體類中的

package aop;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class Person {
    private String message;
    public String getMessage(){
        return message;
    }
    public void setMessage(String message){
        
        this.message=message;
    }
    @PostConstruct
    public void init(){
        System.out.println("開始時先進行初始化"+message);
    }
    @PreDestroy
    public void destroy(){
        System.out.println("結束的時候銷燬"+message);
    }
}