您的位置:首页 > 编程语言 > Java开发

SpringBoot在工具类中注入bean

2017-10-09 00:00 302 查看
摘要: 一般需要在一个工具类中使用@Autowired 注解注入一个service。但在工具类中方法一般都写成static,这样注入不了。

首先你得明白什么是工具类,简单来说它是一种可以不用初始化对象而直接调用其静态方法而达到某一些功能的以Utils或Helper结尾的类。

方案一:间接注入

@Component//泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注//可以换成@Configuration,与@Inject配合使用
public class LuceneIndex {

@Autowired //注意这里非静态//可以换成@Inject
private BootdoConfig bootdoConfig;

private static LuceneIndex luceneIndex;

@PostConstruct //@PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行
public void init() {
luceneIndex = this;
}

private Directory dir=null;

/**
* 获取IndexWriter实例
* @return
* @throws Exception
*/
private IndexWriter getWriter()throws Exception{
/**
* 生成的索引我放在了C盘,可以根据自己的需要放在具体位置
*/
dir= FSDirectory.open(Paths.get(luceneIndex.bootdoConfig.getLucenePath()));
SmartChineseAnalyzer analyzer=new SmartChineseAnalyzer();
IndexWriterConfig iwc=new IndexWriterConfig(analyzer);
IndexWriter writer=new IndexWriter(dir, iwc);
return writer;
}
}

方案二:直接读取文件(未经过测试)

ublic class XMLConfig {
private static final Logger logger = Logger.getLogger(XMLConfig.class);
public static final String            FILEPATH         = "xmlconf.properties";
public static long                    fileLastModified = 0;

//属性文件xmlconf.properties中对应的各个键值对
public static HashMap<String, String> paramsMap    = new HashMap<String, String>();

public static HashMap<String, String> loadProperties(String file)
{
HashMap<String, String> map = new HashMap<String, String>();
InputStream in = null;
Properties p = new Properties();
try
{
in = new BufferedInputStream(new FileInputStream(file));

p.load(in);
}
catch (FileNotFoundException e)
{
logger.error(file + " is not exists!");
}
catch (IOException e)
{
logger.error("IOException when load " + file);
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
logger.error("Close IO error!");
}
}
}

Set<Entry<Object, Object>> set = p.entrySet();
Iterator<Entry<Object, Object>> it = set.iterator();
while (it.hasNext())
{
Entry<Object, Object> entry = it.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
logger.debug(key + "=" + value);
// System.out.println(key + "=" + value);
if (key != null && value != null)
{
map.put(key.trim(), value.trim());
}
}

return map;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  springboot Autowire