常用注解
@component:组件 作用:就是将创建好的对象存入到spring的容器中
@Contoller 通过使用在表现层(控制层)
@Service 通常使用在业务逻辑层上面
@Repository持久的一个注解
@Autowired 自动注入spring中帮助我们创建好的对象
@Qualifier注入 和 @Autowired一起使用
@Resource
@Scope singleton单例的 prototype多例的
@Configuration 指定当前类是一个配置类
细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。
@ComponentScan 用于通过注解指定spring在创建容器时要扫描的包
属性:
value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
我们使用此注解就等同于在xml中配置了:
<context:component-scan base-package="com.itheima"></context:component-scan>
@Bean 用于把当前方法的返回值作为bean对象存入spring容器中
name:用于指定bean的id.当不写时,默认值是当前方法的名称
当我们使用注解配置的方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象,查找的方式和Autowired注解的作用是一样的
@Import
用于导入其他的配置类
属性: value:用于指定其他配置类
当我们使用import的注解之后,有import注解的类就是父配置类,而导入的都是子配置类
@PropertySource
用于指定其他配置类的字节码
关键字:classpath,表示类路径下
主配置类
@ComponentScan("com.itheima") //创建容器时要扫描的包
@Import(JdbcConfig.class) //导入子配置类
@PropertySource("classpath:jdbcConfig.properties") // 指定properties文件位置
public class SpringConfiguration {
}
子配置类
/**
* 和spring连接数据库相关的配置类
*/
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;
/**
* 用于创建一个QueryRunner对象
* @param dataSource
* @return
*/
@Bean(name="runner")
@Scope("prototype") //多例的
public QueryRunner createQueryRunner(@Qualifier("ds2") DataSource dataSource){
return new QueryRunner(dataSource);
}
/**
* 创建数据源对象
* @return
*/
@Bean(name="ds2")
public DataSource createDataSource(){
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
}catch (Exception e){
throw new RuntimeException(e);
}
}