SpringBoot框架下如何实现多线程中【Autowire不好使时】注入对象

阅读更多
需要通过原生Spring获取对象的方式,
1、先编写以下工具类SpringBeanUtil.java
package com.cnd.yourcompany.utils;

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

@Component
public class SpringBeanUtil implements ApplicationContextAware {
	private static ApplicationContext applicationContext = null;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		// TODO Auto-generated method stub
		SpringBeanUtil.applicationContext = applicationContext;
	}

	/**
	 * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
	 */
	@SuppressWarnings("unchecked")
	public static  T getBean(String name) {
		if (name == null || applicationContext == null)
			return null;
		return (T) applicationContext.getBean(name);
	}

	/**
	 * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
	 */
	public static  T getBean(Class clazz) {
		return applicationContext.getBean(clazz);
	}

}

2、映射yml文件的JavaBean
package com.cnd.yourcompany.utils;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "emqx")
public class IvtMqttConfigureInfo {

	private String url;
	
	private int port;
	
	private String username;
	
	private String password;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}
}

3、在业务线程中实现配置文件信息使用
public class MqttClientSubMsgInFuture implements Runnable {

	private IvtMqttConfigureInfo configInfo = SpringBeanUtil.getBean(IvtMqttConfigureInfo.class);
	
	//......
}


4、yml文件配置application.yml如下:
emqx:
  url: www.yourcompany.com
  port: 1883
  username: biz_user
  password: asde13sdeow75x1w

你可能感兴趣的:(Autowire,Component)