使用自定义注解不能全部替代xml配置文件,还要使用到注解代替的配置有:
1.非自定义的bean的配置
2.加载properties文件的配置coontext:property-placeholder
3.组件扫描的配置context:component-scan
4.引入其他文件
spring新注解
|注解|说明|
|@Configuration|用于指定当前类是一个Spring配置类,当创建容器时会从该类上加载注解|
|@ComponentScan|用于指定Spring在初始化时要扫描的包。作用和Spring的xml配置文件中的<context:component-scan beas-package=“com.szl”/>一样|
|@Bean|使用在方法上,标注将该方法的返回值存储到Spring容器中|
|@PropertySource|用于加载.properties文件中中的配置|
|@Import|用于导入其他配置类|
案例
//标志该类是Spring的核心配置类
@Configuration
//自动扫描
@ComponentScan("com.szl")
//加载数据库配置文件中的内容
@PropertySource("classpath:jdbc.properties")
public class SpringConfiguration{
@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("dataSource")//Spring会将当前方法的返回值以指定的名称存储到spring容器中
public DataSource getDataSource() throws Exception{
ComboPooledDataSource dataSource =new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}
在controller中配置加载配置文件类
public calass UserController{
public static void main(String[] args){
ApplicationContext appcontextContext=new AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService.userService=appcontextContext.getBean(UserService.class);
userService.save();
}
}