Spring 实践 -- 获取bean

Spring 实践 

获取实例

 Spring在初始化时容器会根据配置文件初始化所有配置的bean。在使用时有两种常用方法可以在代码中获取实例。

1、@Autowired

系统会自己根据名称、类型去容器里查找对应的类并且注入,前提适用的场景必须是被Spring所扫描到的类,且被注入到容器里。

换句话说就是:

1、被spring扫描到。

<context:component-scan base-package="com.rest.server"/>

2、类被注解标记。

@Service告诉spring容器,这是一个Service类,标识持久层Bean组件,默认情况会自动加载它到spring容器中。 

@Autowried注解告诉spring,这个字段需要自动注入 

@Scope指定此spring bean的scope是单例 

@Repository注解指定此类是一个容器类,是DA层类的实现。标识持久层Bean组件 

@Componet:基本注解,标识一个受Spring管理的Bean组件 

@Controller:标识表现层Bean组件

2、ApplicationContextAware

在项目中,会遇到一些在非容器环境下还要获取容器组件的情况,比如定时器job,在job我们会有一些数据库操作,业务层调用,这时通过@Autowired这种方式就会报null。这时就得让job获取它所在的容器

1、spring配置文件中申明

<bean id="SpringBeanUtil" class="com.util.SpringBeanUtil"/>

2、编写SpringBeanUtil

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

public class SpringBeanUtil implements ApplicationContextAware {

    private static ApplicationContext context = null;
    private static SpringBeanUtil stools = null;

    public synchronized static SpringBeanUtil init() {
        if (stools == null) {
            stools = new SpringBeanUtil();
        }
        return stools;
    }

    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        context = applicationContext;
    }

    public synchronized static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    public synchronized static Object getBean(Class c) {
        return context.getBean(c);
    }

}

3、代码使用

SendNoticeService sendNoticeService = (SendNoticeService) SpringBeanUtil.getBean(SendNoticeService.class);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值