spring 获取bean的几种方式

本文详细介绍了在Spring框架中获取ApplicationContext的多种方法,包括直接读取XML配置文件、继承Aware类、使用工具类等,适用于不同场景下对Spring上下文的灵活运用。

1.读取xml文件的方式,这种在初学入门的时候比较适用 。

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:tt.xml");

    ApplicationContext applicationContext = new FileSystemXmlApplicationContext("classpath:tt.xml");

2.继承spring的Aware类,覆盖方法实现获取上下文,从上下文中获取。

    2.1.继承自抽象类ApplicationObjectSupport
    说明:抽象类ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取到ApplicationContext。
    Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。

    2.2:继承自抽象类WebApplicationObjectSupport
    说明:类似上面方法,调用getWebApplicationContext()获取WebApplicationContext

    2.3:实现接口ApplicationContextAware
     说明:实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。
    Spring初始化时,会通过该方法将ApplicationContext对象注入。

3.借助于spring提供的工具类,

    WebApplicationContextUtils.getWebApplicationContext(ServletContext) 需要传入Servletcontext ,

    通常从request中获取req.getSession().getServletContext()。适合于controller或者action中直接获取,但通常会直接@autoWire注入。

package com.controller;

import com.properties.Properties;
import com.service.IMyService;
import com.util.BeanUtil;
import com.util.BeanUtil1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import reactor.core.publisher.Mono;
import sun.misc.Request;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

/**
 * @author wanjiadong
 * @description
 * @date Create in 10:14 2018/9/4
 */
@RestController
@RequestMapping("/test")
//@EnableAutoConfiguration
public class testController implements ApplicationListener<ContextRefreshedEvent> {

    private ApplicationContext context = null;
    
    @Autowired
    private IMyService myService1;

    @Value("${test.server.name:haha}")
    private String testServerName;

    @Autowired
    private Properties properties;

    @Autowired
    private BeanUtil1 beanUtil1;

    @RequestMapping("/sayHello")
    public String sayHello(HttpServletRequest request) {
//        myService1.sayHello();
//        ContextLoader.getCurrentWebApplicationContext().getBean("properties");
        Properties properties1 = BeanUtil.getBean("properties");
        Properties properties2 = (Properties) context.getBean("properties");
        Properties properties3 = (Properties) WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean("properties");
        Properties properties4 = beanUtil1.getBean("properties");
        return properties1.getTestServerName();
    }

    @GetMapping("/getWebFlux")
    public Mono<String> getWebFlux() {
        return Mono.just("getWebFlux");
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if(null != contextRefreshedEvent) {
            context = contextRefreshedEvent.getApplicationContext();
        }
    }
}
package com.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author wanjiadong
 * @description
 * @date Create in 11:25 2018/12/28
 */
@Component
public class BeanUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    public static <T> T getBean(String beanName) {
        return (T) context.getBean(beanName);
    }

    public static <T> T getBean(Class<?> var1) {
        return (T) context.getBean(var1);
    }
}
package com.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Component;

/**
 * @author wanjiadong
 * @description
 * @date Create in 11:55 2018/12/28
 */
@Component
public class BeanUtil1 extends ApplicationObjectSupport {

    private ApplicationContext context;

    public <T> T getBean(String beanName) {
        context = getApplicationContext();
        return (T) context.getBean(beanName);
    }
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

41摄氏度男

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值