- 属性占位符适配器是在配置文件中配置一个属性占位符适配器的bean A,然后bean A加载配置文件,然后其他bean就可以通过占位符的方式去使用属性占位符适配器已经加载好的值。
- 这种办法可以当相应的信息需要修改的时候不用改beans.xml,直接在属性文件里边改就可以了。
- 代码这里就不真的链接数据库了,其实链接也很简单,是把~
package DbPackage; //这是普通bean,可以通过占位符的方式使用属性占位符适配器已经配置好的属性值 public class Db { private String driver; private String url; private String user; private String pass; public void setDriver(String driver) { this.driver = driver; } public String getDriver() { return driver; } public String getUrl() { return url; } public String getUser() { return user; } public String getPass() { return pass; } public void setUrl(String url) { this.url = url; } public void setUser(String user) { this.user = user; } public void setPass(String pass) { this.pass = pass; } }
package TestPackage; import DbPackage.Db; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; //测试类 public class SpringTest { public static void main(String []args){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); Db db = applicationContext.getBean("dataSource", Db.class); System.out.println(db.getDriver()); } }
<?xml version="1.0" encoding="GBK"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <!--这就是属性占位符适配器,无需指定id。实现类是PropertyPlaceholderConfigurer--> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>dbconn.properties</value> </list> </property> </bean> <!--通过占位符的方式获得相应的值,注意名字要写对--> <bean id="dataSource" class="DbPackage.Db" p:driver="${driver}" p:url="${url}" p:user="${user}" p:pass="${driver}" /> </beans>
driver = com.microsoft.sqlserver.jdbc.SQLServerDriver url = jdbc:sqlserver://localhost:1433; DatabaseName=homework_Submit_System user = root pass = 123456
这是我看李刚编著的《轻量级javaEE企业应用实战(第五版)-Struts2+Spring5+Hibernate5/JAP2》后总结出来的。
Spring 进阶(3) 属性占位符适配器
猜你喜欢
转载自blog.csdn.net/weixin_39452731/article/details/84890583
今日推荐
周排行