spring init

发布时间:2025-05-06 17:01

Java后端开发:Spring Boot框架入门 #生活技巧# #工作学习技巧# #编程语言学习路径#

最新推荐文章于 2025-04-01 03:16:04 发布

peerless_fu 于 2018-11-21 08:47:19 发布

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

在项目中曾多次看到init-method和destroy方法的相关配置,今天特地具体的了解了一下,简单说说几种使用方法。

1、java形式的配置方式:

package com.fyf.service;

public class BeanCreateService {

public void init(){

System.out.println("init(),在BeanCreateService bean初始化完之后执行。");

}

public BeanCreateService(){

super();

System.out.println("BeanCreateService bean的初始化构造函数。");

}

public void destroy(){

System.out.println("destroy(),在BeanCreateService bean销毁后执行。");

}

}

2、-250的方式:

package com.fyf.service;

import javax.annotation.PostConstruct;

import javax.annotation.PreDestroy;

public class JSR250BeanCreateService {

@PostConstruct

public void init(){

System.out.println("init(),在JSR250BeanCreateService bean初始化完之后执行。");

}

public JSR250BeanCreateService(){

super();

System.out.println("JSR250BeanCreateService bean的初始化构造函数。");

}

@PreDestroy

public void destroy(){

System.out.println("destroy(),在JSR250BeanCreateService bean销毁后执行。");

}

}

编写我们的配置bean:

package com.fyf.config;

import com.fyf.service.BeanCreateService;

import com.fyf.service.JSR250BeanCreateService;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

@Configuration

@ComponentScan("com.fyf")

public class BeanConfig {

@Bean(initMethod = "init", destroyMethod = "destroy")

BeanCreateService beanCreateService(){

return new BeanCreateService();

}

@Bean

JSR250BeanCreateService jsr250BeanCreateService(){

return new JSR250BeanCreateService();

}

}

最后编写一个测试类:

package com.fyf.controller;

import com.fyf.config.BeanConfig;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestController {

public static void main(String[] args) {

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);

context.close();

}

}

 我们来看下运行的结果:

BeanCreateService bean的初始化构造函数。
init(),在BeanCreateService bean初始化完之后执行。
JSR250BeanCreateService bean的初始化构造函数。
init(),在JSR250BeanCreateService bean初始化完之后执行。
destroy(),在JSR250BeanCreateService bean销毁后执行。
destroy(),在BeanCreateService bean销毁后执行。
 

还有一种就是放在配置文件里的,大概是这样子的:

<bean id="person" class="com.fyf.service.BeanCreateService" lazy-init="false" init-method="init"

destroy-method="destory"></bean>

效果都是一样的。

网址:spring init https://www.yuejiaxmz.com/news/view/935730

相关内容

Spring全注解开发
spring
@EnableRetry(proxyTargetClass = true) . spring
Spring Integration关键案例与现实生活场景 spring的应用场景
spring事务管理(详解和实例)
关于Spring 中的 IoC
spring clean什么意思
spring cleaning什么意思
spring boot 获取天气预报
大扫除为什么叫spring cleaning

随便看看