普通Java类获取Spring Bean的实现方式

洼地云 ai-quyi.png

方式1:实现ApplicationContextAware接口

步骤:

1.写一个工具类,实现ApplicationContextAware接口;
2.将此工具类在spring配置文件中配置;
3.在类中调用;

工具类代码:

public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext context;//声明一个静态变量保存
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    public static ApplicationContext getContext(){
        return context;
    }
}

配置applicationContext.xml文件

<bean id="springContextUtil" class="com.netsdk.util.SpringContextUtil"></bean>

使用


HashMap<String,String> map = new HashMap<>(); map.put("ID", UUID.randomUUID().toString()); map.put("ALARM_TIME",DateUtils.date2Str(DateUtils.datetimeFormat)); map.put("ALARM_TYPE","闯入告警"); ap.put("DEVICE_IP","192.168.0.98"); VideoMonitorService service = (VideoMonitorService) SpringContextUtil.getContext().getBean("videoMonitorService"); service.insertVideoAlarmInfo(map);
赞(0)
未经允许禁止转载:优米格 » 普通Java类获取Spring Bean的实现方式

评论 抢沙发

合作&反馈&投稿

商务合作、问题反馈、投稿,欢迎联系

广告合作侵权联系

登录

找回密码

注册