SpringBoot在工具类中注入bean

原创
2017/10/09 20:49
阅读数 9.8K

首先你得明白什么是工具类,简单来说它是一种可以不用初始化对象而直接调用其静态方法而达到某一些功能的以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;
      }

}

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部