Spring 基于JSR-250注释包括 @PostConstruct, @PreDestroy 和 @Resource 注释
    @PostConstruct 注释替代了初始化回调函数
    @PreDestroy 注释替代了销毁回调函数
    @Resource 注释使用一个 name 属性,该属性以一个 bean 名称的形式被注入。遵循 by-name 自动连接语义。如果没有明确地指定一个 ‘name’,默认名称源于字段名或者 setter 方法。在字段的情况下,它使用的是字段名;在一个 setter 方法情况下,它使用的是 bean 属性名称。
    使用 @PostConstruct 、 @PreDestory 和 @Resource 时,需要在配置文件中添加以下代码

    1. 在 beans 中添加 xmlns:context 属性
    2. xmlns:context="http://www.springframework.org/schema/context"
    3. 在 beans 的 xsi:schemaLocation 属性中添加并用空格分隔
    4. http://www.springframework.org/schema/context
    5. http://www.springframework.org/schema/context/spring-context-3.0.xsd
    6. beans 内添加
    7. <context:annotation-config/>

    案例代码:
    Person.java

    1. package com.baklib.hello;
    2. public class Person {
    3. private String name;
    4. private Integer age;
    5. public String getName() {
    6. return name;
    7. }
    8. public void setName(String name) {
    9. this.name = name;
    10. }
    11. public Integer getAge() {
    12. return age;
    13. }
    14. public void setAge(Integer age) {
    15. this.age = age;
    16. }
    17. }

    Action.java

    1. package com.baklib.hello;
    2. import javax.annotation.Resource;
    3. public class Action {
    4. @Resource(name="person")
    5. private Person person;
    6. public void sayHello(){
    7. System.out.println("Hello, "+person.getName()+" is "+person.getAge());
    8. }
    9. }

    MainApp.java

    1. package com.baklib.hello;
    2. import org.springframework.context.ApplicationContext;
    3. import org.springframework.context.support.ClassPathXmlApplicationContext;
    4. public class MainApp {
    5. public static void main(String[] args) {
    6. ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
    7. Action action = (Action) context.getBean("action");
    8. action.sayHello();
    9. }
    10. }

    配置文件 Beans.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:context="http://www.springframework.org/schema/context"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    6. <context:annotation-config/>
    7. <bean id="action" class="com.baklib.hello.Action"></bean>
    8. <bean id="person" class="com.baklib.hello.Person">
    9. <property name="name" value="张三" />
    10. <property name="age" value="22" />
    11. </bean>
    12. </beans>

    编写完以上代码,就可以运行这个程序,运行结束后,可以在控制台看到下面的信息

    1. Hello, 张三 is 22