文章目录
一、常用注解
1、用于 创建对象 的注解
- 相当于:
<bean id="" class="">
@Component
@Controller
、@Service
、@Repository
2、用于 注入数据 的注解
- 相当于:
<property name="" ref="">
和<property name="" value="">
@Autowired
(按类型注入)
@Qualifier
(按名称注入)
@Value
3、用于 改变作用范围 的注解
- 相当于:
<bean id="" class="" scope="">
@Scope
二、从xml到纯注解的替换过程
1、使用@Component 替换 < bean>
@Component("accountDao") //accountDao为bean的id
public class AccountDaoImpl implements IAccountDao {
private DBAssit dbAssit;
}
2、用@Configuration配置类去替换配置文件
@Configuration
- 代码示例
@Configuration
public class SpringConfiguration {
}
3、用@ComponentScan替换< context:component-scan>
@Configuration
@ComponentScan("com.demo。springtest")
public class SpringConfiguration {
}
4、再用一个配置类来封装数据库的相关配置
- 先将数据库的配置信息单独抽取出来写在
.properties
配置文件,方便后期的修改
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=123456
- 利用
@PropertySource
引入jdbc.properties配置文件
@Configuration
@PropertySource("classpath:jdbc.properties")
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;
/*创建一个数据源,并存入 spring 容器中*/
@Bean(name="dataSource")
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);
}
}
}
5、用@Import整合多个配置类
@Configuration
@ComponentScan(basePackages = "com.itheima.spring")
@Import({ JdbcConfig.class})
public class SpringConfiguration {...}
6、没有配置文件时是如何获取容器的
//获取容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//通过容器对象得到想要的业务层对象
IAccountService as = ac.getBean("accountService",IAccountService.class);