Spring基于注解配置(一)

1.@Bean注解指定init-method和destory-method

这里创建一个Car类,给类加上无参的构造函数,并定义两个方法init()和destory()

 1 public class Car {
 2 
 3     public Car() {
 4         System.out.println("car constructor....");
 5     }
 6     
 7     public void init() {
 8         System.out.println("car init.....");
 9     }
10     
11     
12     public void detory() {
13         System.out.println("car detory.....");
14     }
15     
16 }

创建一个配置类,并给initMethod和destroyMethod指定Car类中的init()和detory()

//指定配置类
@Configuration
public class MainConfigOfLifeCycle {
        //给容器中注册bean
    @Bean(initMethod="init",destroyMethod="detory")
    public Car car() {
        return new Car();
    }
}

然后可以在测试类中测试

@Test
    public void testIOC() {
        //创建ioc容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
        //手动关闭容器
        applicationContext.close();
    }

2.通过让bean实现InitializingBean(定义初始化),DisposableBean(定义销毁)

创建一个类实现InitializingBean接口和DisposableBean接口

@Component//如果不想使用@Component可以在配置类中注册Cat
public class Cat implements InitializingBean,DisposableBean {

    public Cat() {
        System.out.println("cat constructor.....");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("cat destory......");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("cat   afterPropertiesSet.....");
    }
}

在配置类中在加上@ComponentScan(因为Cat类被@Component标识)

@ComponentScan("com.spring.bean")

然后可以在测试类中测试

 

posted @ 2020-05-27 10:48  丶栀爱  阅读(151)  评论(0)    收藏  举报