欢迎光临
一个废柴的博客

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

方式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);

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址