spring17:Bean的生命始末标签@PostConstruct,@PreDestroy和改变作用范围的@Scope标签
生活随笔
收集整理的這篇文章主要介紹了
spring17:Bean的生命始末标签@PostConstruct,@PreDestroy和改变作用范围的@Scope标签
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Bean的生命始末標簽@PostConstruct,@PreDestroy?
package com.atChina.Test8;import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service;/** @Component: 創(chuàng)建對象,默認創(chuàng)建的是單例對象* 屬性: value,表示對象的id* 位置: 在類的上面,表示創(chuàng)建該類的對象* @Component(value="myStudent")等同于<bean id="myStudent" class="com.atChina.Test.Student" /> * */ @Component("student") public class Student {@Value("宋江")private String name;private int age;/** 引用類型,使用框架的自動注入: * @Resource:來自jdk中的注釋,給引用類型賦值,支持byName,byType. 默認是byName* 位置:1)在屬性定義的上面,推薦使用,無需set方法* 2)在set方法的上面*/@Resource(name="sch") // 只按byName,需要指定@Resource的name屬性,name指定bean對象的名稱private School school;public void setName(String name) {System.out.println("setName:"+name);this.name = name;}@Value("23")public void setAge(int age) {System.out.println("setAge:"+age);this.age = age;}// 定義bean的初始化方法@PostConstructpublic void studentInit(){System.out.println("bean的初始化方法:等同于配置文件的init-method方法");}// 定義bean的銷毀方法@PreDestroypublic void studentDestroy(){System.out.println("bean的銷毀方法:等同于配置文件的destroy-method方法");}@Overridepublic String toString() {return "Student [name=" + name + ", age=" + age + ", school=" + school+ "]";} }測試方法:?
@Testpublic void test1(){String configLocation = "com/atChina/Test8/applicationContext.xml"; // 類路徑的根目錄ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocation);Student ss = (Student)ctx.getBean("student");System.out.println("stduent:"+ss);((ClassPathXmlApplicationContext)ctx).close(); // 關(guān)閉spring容器}?測試結(jié)果:
?
改變作用范圍的@Scope標簽
?
總結(jié)
以上是生活随笔為你收集整理的spring17:Bean的生命始末标签@PostConstruct,@PreDestroy和改变作用范围的@Scope标签的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring:注解@Resource,实
- 下一篇: spring18:aop介绍