使用@Component注解替代xml中的
BookDaoImpl
- @Component("bookDao")
- public class BookDaoImpl implements BookDao {
- public void save() {
- System.out.println("book dao save ..." );
- }
- }
去掉xml的bean后,spring需要知道哪些package下有bean,所以需要在xml中添加以下配置:
<context:component-scan base-package="com.lan"/>
下面讲解不需要任何xml配置的纯注解开发模式
SpringConfig
- package com.lan.config;
-
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.context.annotation.Configuration;
-
- //声明当前类为Spring配置类
- @Configuration
- //设置bean扫描路径,多个路径书写为字符串数组格式
- @ComponentScan({"com.lan.service","com.lan.dao"})
- public class SpringConfig {
- }
- // 根据SpringConfig去初始化IOC容器
- ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
- BookDao bookDao = (BookDao) ctx.getBean("bookDao");
该注解相当于
- @Scope("singleton") // 默认值是singleton,可选prototype
- @Component("bookDao")
- public class BookDaoImpl implements BookDao {
- public void save() {
- System.out.println("book dao save ..." );
- }
- }
分别对应
该注解根据类型自动注入bean,可以用于成员变量、构造方法、setter方法
- @Autowired // 根据类型自动注入,注入BookDao类型的bean
- private BookDao bookDao;
该注解根据bean的id自动注入bean,但不能单独使用,需要和@Autowired一起配合使用
- @Autowired // 根据类型自动注入,注入BookDao类型的bean
- @Qualified("bookDao") // 配合@Autowired一起使用,根据bean id自动注入bean
- private BookDao bookDao;
配置类上使用@PropertySource加载properties文件
- package com.lan.config;
-
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.context.annotation.Configuration;
-
- //声明当前类为Spring配置类
- @Configuration
- //设置bean扫描路径,多个路径书写为字符串数组格式
- @ComponentScan({"com.lan.service","com.lan.dao"})
- @PropertySource({"jdbc.properties", "xxx.properties"}) // 指定要加载的properties文件
- public class SpringConfig {
- }
在bean里使用@Value注入对应的变量
- @Value("${spring.datasource.username}") // 注入变量
- private String username;
-
- @Value("100") // 注入常量
- private int scope;
直接使用@Bean注解创建并管理第三方bean
- @Configuration
- public class SpringConfig {
- @Bean
- public DataSource dataSource(){
- DruidDataSource ds = new DruidDataSource();
- ds.setDriverClassName("com.mysql.jdbc.Driver");
- ds.setUrl("jdbc:mysql://localhost:3306/spring_db");
- ds.setUsername("root"); ds.setPassword("root");
- return ds;
- }
-
- @Bean
- public DataSourceWrapper dataSourceWrapper(DataSource datasource) { // 依赖其它bean
- return new DataSourceWraper(datasource);
- }
- }
通过Import导入配置类,导入的类也会成为bean
SpringConfig
- @Configuration
- @Import(JdbcConfig.class) // 导入该类,该类可以位于其它package下
- public class SpringConfig {
- }
JdbcConfig
- public class JdbcConfig { // 该类不用加注解
- @Value("${datasource.username}")
- private String username;
- @Value("${datasource.password}")
- private String password;
- @Value("${datasource.driverClassName}")
- private String driverClassName;
- @Value("${datasource.jdbcUrl}")
- private String jdbcUrl;
-
- @Bean
- public DataSource dataSource(){
- DruidDataSource ds = new DruidDataSource();
- ds.setDriverClassName(driverClassName);
- ds.setUrl(jdbcUrl);
- ds.setUsername(username);
- ds.setPassword(password);
- return ds;
- }
- }
maven依赖
- <dependency>
- <groupId>junitgroupId>
- <artifactId>junitartifactId>
- <version>4.12version>
- <scope>testscope>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-testartifactId>
- <version>5.2.10.RELEASEversion>
- dependency>
测试类
- package com.itheima.service;
-
- import com.itheima.config.SpringConfig;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
- //设置类运行器
- @RunWith(SpringJUnit4ClassRunner.class)
- //设置Spring环境对应的配置类
- @ContextConfiguration(classes = SpringConfig.class)
- public class AccountServiceTest {
- //支持自动装配注入bean
- @Autowired
- private AccountService accountService;
-
- @Test
- public void testFindById(){
- System.out.println(accountService.findById(1));
- }
-
- @Test
- public void testFindAll(){
- System.out.println(accountService.findAll());
- }
- }
新增maven依赖,用于自动生成Mybatis相关的bean
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatis-springartifactId>
- <version>1.3.0version>
- dependency>
SpringConfig
- @Configuration
- @Import(MybatisConfig.class)
- public class SpringConfig {
- }
MybatisConfig
- package com.lan.config;
-
- import org.mybatis.spring.SqlSessionFactoryBean;
- import org.mybatis.spring.mapper.MapperScannerConfigurer;
- import org.springframework.context.annotation.Bean;
-
- import javax.sql.DataSource;
-
- public class MybatisConfig {
- //定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象
- @Bean
- public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
- SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
- ssfb.setTypeAliasesPackage("com.itheima.domain");
- ssfb.setDataSource(dataSource);
- return ssfb;
- }
- //定义bean,返回MapperScannerConfigurer对象
- @Bean
- public MapperScannerConfigurer mapperScannerConfigurer(){
- MapperScannerConfigurer msc = new MapperScannerConfigurer();
- msc.setBasePackage("com.itheima.dao");
- return msc;
- }
- }
使用Mybatis操作接口
- ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
- AccountService accountService = ctx.getBean(AccountService.class);
- Account ac = accountService.findById(1);