今天胡老师询问是否可以在java中读取配置文件,并询问了java操纵数据库的情况。我都给出了肯定的回答。晚上上不了迅雷看看,随手从以前的代码中按照胡老师的需要抽取了一部分,装配成型。主要用到的Spring的ioc,jdbctmplate,以及rowmapper。上代码:
package sever.bean; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class GetBean { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context = new ClassPathXmlApplicationContext( "beans-config.xml"); Settings settings = (Settings) context.getBean("settings"); System.out.println("the config1 of Settings is: " + settings.getConfig1()); SimpleJdbcUtil sju = new SimpleJdbcUtil(); User[] users = sju.fetchall(); for (User u : users) { System.out.println("the name of User u is: " + u.getUserName()); } } }
package sever.bean; public class SimpleJdbcUtil extends SpringJdbcUtil { @SuppressWarnings("unchecked") public User[] fetchall() { String sql = "select * from user"; return (User[]) this.getJdbcTemplate().query(sql, new UserRowMapper()) .toArray(new User[0]); } }
package sever.bean; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class UserRowMapper implements RowMapper { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { // TODO Auto-generated method stub String username = rs.getString("username"); String password = rs.getString("password"); String email = rs.getString("email"); String phoneNO = rs.getString("phoneno"); String phoneNO1 = rs.getString("phoneno1"); String phoneNO2 = rs.getString("phoneno2"); String companyname = rs.getString("companyname"); String address = rs.getString("address"); User user = new User(username, password, email, phoneNO, phoneNO1, phoneNO2, companyname, address); return user; } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>Config.txt</value> </list> </property> </bean> <bean id="settings" class="sever.bean.Settings" destroy-method="close"> <property name="config1" value="${Config.config1}" /> </bean> </beans>
# Properties file with JDBC-related settings. # Applied by PropertyPlaceholderConfigurer from "applicationContext.xml". # Targeted at system administrators, to avoid touching the context XML files. Config.config1=I am config1 # Config.config2=I am config2