若有properties文件需要导入,那么应在主配置类上添加注解@PropertySource("classpath:文件名(Resourse下的文件名)")
这样在主配置类或者子配置类都可以用注解@Value("${key}")
给成员变量注入值。
比如父配置类为
@Configuration
@ComponentScan(basePackages = "com.HSY")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration
{
@Bean(name="runner")
public QueryRunner createQueryRunner(DataSource dataSource)
{
return new QueryRunner(dataSource);
}
}
则子配置类为
public class JdbcConfig
{
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean(name="dataSource")
public DataSource createDataSource()
{
ComboPooledDataSource cd = new ComboPooledDataSource();
try
{
cd.setDriverClass(driver);
cd.setJdbcUrl(url);
cd.setUser(username);
cd.setPassword(password);
}
catch (PropertyVetoException e)
{
e.printStackTrace();
}
return cd;
}
}