之前在项目里面连接数据库需要将密码解密,而且连接好多数据库,并且有的数据库需要解密有的直接连接就可以。
这样代码的可读性特别低,在连接数据库的时候都要现连接:
Properties prop = new Properties();
prop.load(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("lecture.properties"));
Session s = Session.getInstance(prop);
// OA数据库连接地址
String oaIp = s.getProperty("oaIp");
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:" + "thin:@" + oaIp;
// OA用户名
String user = s.getProperty("oaUsername");
// OA密码
String password = s.getProperty("oaPassword");
PropertiesEncryptFactoryBean encryptor = new PropertiesEncryptFactoryBean();
那么我们可以将数据库的连接信息放到配置文件里面,并且在配置文件解密,这样在连接数据库的时候只需在选择加载那个连接:
(1)在spring的某一个xml配置文件中加入加载解密的配置属性代码:
这里的classpath一定别写错了
class="org.jasypt.spring.properties.EncryptablePropertyPlaceholderConfigurer">
classpath:config.properties
(2)数据源配置(3)在相应的需要加载哪一个数据库:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring/datasource.xml");
DriverManagerDataSource dataSource=(DriverManagerDataSource) applicationContext.getBean("OAdataSource");
System.out.println(dataSource.getUrl());
con=dataSource.getConnection();
System.out.println("OA数据库连接成功!");(4)另外在数据库配置文件中config.properties文件中,如果哪一个需要解密,那么需要加上前缀ENC(**********):
password=ENC(********)