Spring容器注入bean

本文介绍了SpringMVC项目中Spring容器如何注入bean的方法,包括使用@PostConstruct和@PreDestroy注解、XML配置文件中的init-method和destroy-method属性、以及实现InitializingBean和DisposableBean接口。文中还详细展示了通过XML配置bean的实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringMVC项目, Spring容器注入bean的操作方法:


第一种:通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
第二种是:通过 在xml中定义init-method 和  destory-method方法
第三种是: 通过bean实现InitializingBean和 DisposableBean接口


一般常用第二种,通过xml 配置通常要使用下面几个属性:
init-method: 初始化执行
destroy-method: 销毁时执行
constructor-arg :设置bean构造器,第0个参数的值
property: 设置bean类属性的值


项目具体配置方法如下


web.xml配置:
<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext-service.xml
        </param-value>
 </context-param>


applicationContext-service.xml配置:


<bean id="httpClientManager" class="com.jdj.common.utils.HttpClientManager"
        init-method="closeIdleStart" destroy-method="destory">
        <constructor-arg index="0" name="connectionTimeOut"
            value="5000" />  
        <constructor-arg index="1" name="soTimeOut" value="500000" />
        <property name="maxTotal" value="1023" />
    </bean>


SpringMVC注入bean操作


init-method: 初始化执行


destroy-method: 销毁时执行


constructor-arg :设置bean构造器,第0个参数的值


property: 设置bean类属性的值




bean调用


 public static void main(String[] args) { 


      AbstractApplicationContext  context =new  ClassPathXmlApplicationContext("SpringBeans.xml"); 


    PersonService  person = (PersonService)context.getBean("personService"); 


    person.setMessage("hello  spring"); 


    PersonService  person_new = (PersonService)context.getBean("personService"); 


    System.out.println(person.getMessage()); 
    System.out.println(person_new.getMessage()); 
    context.registerShutdownHook();  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值