我正在尝试使用Spring 3实现不同配置文件的应用程序,但我不确定它是如何使用Spring 3开发的。我有几个混淆
以下是我的申请表
这是简单模型对象。
** Employee.Java **
public class Employee {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
此类处理数据库。所以我想在这个类而不是Datasource对象中拥有会话对象。
员工DAO课程
public class EmployeeDao {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void insert(Employee employee){
String sql = "insert into employee(name) VALUES (?)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, employee.getName());
ps.executeUpdate();
ps.close();
conn.close();
}
catch (SQLException sqle) {
System.out.println("Sql Exception " + sqle.getMessage());
}
}
这个类实际上从属性文件中读取数据,但不确定如何构建在我的DAO类中注入的会话对象
Config.java
public class Config {
@Bean
public static PropertyPlaceholderConfigurer properties(){
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ClassPathResource[] resources = new ClassPathResource[ ]
{ new ClassPathResource( "db.properties" ) };
ppc.setLocations( resources );
ppc.setIgnoreUnresolvablePlaceholders( true );
return ppc;
}
@Value( "${jdbc.url}" ) private String jdbcUrl;
@Value( "${jdbc.driverClassName}" ) private String driverClassName;
@Value( "${jdbc.username}" ) private String username;
@Value( "${jdbc.password}" ) private String password;
@Bean(name="datasource")
public DataSource datasource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(driverClassName);
ds.setUrl(jdbcUrl);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
@Bean(name="employee")
public Employee employee() {
Employee employee = new Employee();
employee.setName("Sahil");
return employee;
}
@Bean(name="employeeDao")
public EmployeeDao employeeDao() {
EmployeeDao employeeDao = new EmployeeDao();
employeeDao.setDataSource(datasource());
return employeeDao;
}