當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring中的Spring JSR-250 注释
生活随笔
收集整理的這篇文章主要介紹了
Spring中的Spring JSR-250 注释
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Spring還使用基于 JSR-250 注釋,它包括 @PostConstruct, @PreDestroy 和 @Resource 注釋。
@PostConstruct 和 @PreDestroy 注釋
為了定義一個 bean 的安裝和卸載,我們使用?init-method?和/或?destroy-method?參數簡單的聲明一下?。init-method 屬性指定了一個方法,該方法在 bean 的實例化階段會立即被調用。同樣地,destroy-method 指定了一個方法,該方法只在一個 bean 從容器中刪除之前被調用。
你可以使用?@PostConstruct?注釋作為初始化回調函數的一個替代,@PreDestroy?注釋作為銷毀回調函數的一個替代,看一個具體的例子來學習。
HelloWorld:
package com.sap;import javax.annotation.*;public class HelloWorld {private String message;public void setMessage(String message){this.message = message;}public String getMessage(){System.out.println("Your Message : " + message);return message;}@PostConstructpublic void init(){System.out.println("Bean is going through init.");}@PreDestroypublic void destroy(){System.out.println("Bean will destroy now.");}}在Main.app里注冊一個關閉鉤?registerShutdownHook()?方法,該方法在 AbstractApplicationContext 類中被聲明。
import org.springframework.context.support.AbstractApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class MainApp {public static void main(String[] args) {AbstractApplicationContext context =new ClassPathXmlApplicationContext("Beans.xml");HelloWorld obj = (HelloWorld) context.getBean("helloWorld");obj.getMessage();context.registerShutdownHook();}}Beans.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"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd"><context:annotation-config/><bean id="helloWorld"class="com.sap.HelloWorld"init-method="init" destroy-method="destroy"><property name="message" value="Hello World!"/></bean></beans>輸出:
總結
以上是生活随笔為你收集整理的Spring中的Spring JSR-250 注释的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3D怎么制作漂亮的五彩烟灰缸模型
- 下一篇: 接力贷是什么意思接力贷申请条件有哪些