通过spring boot 启动加载自己编写的properties数据库配置文件,从而进行系统的参数读取及配置信息。不用spring boot 中的jdbctemplate。
步骤:
一、编写properties文件, 放置到resource目录下(我的命名为:dbConfig.properties)
url=jdbc:mysql://127.0.0.1/jxsystem?serverTimezone=UTC&useUnicode=true&charaterEncoding=utf-8&useSSL=false name=com.mysql.cj.jdbc.Driver user=root password=mysql
二、编写PropertyUtil.java读取配置类
public class PropertyUtil { private static Map<String, String> propertiesMap = new HashMap<>(); // Default as in PropertyPlaceholderConfigurer public static void processProperties( Properties props) throws BeansException { propertiesMap = new HashMap<String, String>(); for (Object key : props.keySet()) { String keyStr = key.toString(); try { //PropertiesLoaderUtils的默认编码是ISO-8859-1,在这里转码一下 propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1"),"utf-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }catch (java.lang.Exception e){ e.printStackTrace(); }; } System.out.println(propertiesMap); } public static void loadAllProperties(){ try { Properties properties = PropertiesLoaderUtils.loadAllProperties("dbConfig.properties"); processProperties(properties); } catch (IOException e) { e.printStackTrace(); } } public static String getProperty(String name) { //如果系统启动加载时,没有读到信息,则进行一次补读 if(propertiesMap.size()==0){ loadAllProperties(); } return propertiesMap.get(name).toString(); } }
以上方法基本上是可以读取到properties文件中的信息了,如果是想在spring boot 启动中时读取,则需要以下一个监听器并且需要通过修改Application.java文件
三、编写ApplicationStartUpListener.java监听器类
public class ApplicationStartUpListener implements ApplicationListener<ApplicationStartedEvent> { @Override public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) { PropertyUtil.loadAllProperties(); System.out.println("ApplicationStartUpListener EXEC"); } }
四、修改Application.java文件
@SpringBootApplication public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication application = new SpringApplication(Application.class); application.addListeners(new ApplicationStartUpListener()); application.run(args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(Application.class); } }
以上仅共学习。