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: 创建对象,默认创建的是单例对象
* 属性: value,表示对象的id
* 位置: 在类的上面,表示创建该类的对象
* @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的初始化方法
@PostConstruct
public void studentInit(){
System.out.println("bean的初始化方法:等同于配置文件的init-method方法");
}
// 定义bean的销毁方法
@PreDestroy
public void studentDestroy(){
System.out.println("bean的销毁方法:等同于配置文件的destroy-method方法");
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", school=" + school
+ "]";
}
}
测试方法:
@Test
public 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(); // 关闭spring容器
}
测试结果:
改变作用范围的@Scope标签