1. 基于注解的改造
使用@Component 注解配置管理的资源
@Component("accountService")
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
}
@Component("accountDao")
public class AccountDaoImpl implements IAccountDao {
private DBAssit dbAssit;
}
当我们使用注解注入时,set 方法不用写
创建 spring 的 xml 配置文件并开启对注解的支持
基于注解整合时,导入约束时需要多导入一个 context 名称空间下的约束。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 告知 spring 创建容器时要扫描的包 -->
<context:component-scan base-package="org.woster"></context:component-scan>
<!-- 配置 dbAssit -->
<bean id="dbAssit" class="org.woster.dbassit.DBAssit">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///test"></property>
<property name="user" value="root"></property>
<property name="password" value="1234"></property>
</bean>
</beans>
2. 常用注解
2.1 用于创建对象的
@Component
- 作用:把资源让 spring 来管理。相当于在 xml 中配置一个 bean。
- 属性:
- value:指定 bean 的 id。如果不指定 value 属性,默认 bean 的 id 是当前类的类名。首字母小写。
@Controller @Service @Repository
他们三个注解都是针对一个的衍生注解,他们的作用及属性都是一模一样的。
他们只不过是提供了更加明确的语义化。
- @Controller:一般用于表现层的注解。
- @Service:一般用于业务层的注解。
- @Repository:一般用于持久层的注解。
如果注解中有且只有一个属性要赋值时,且名称是 value,value 在赋值是可以不写。
2.2 用于注入数据的
@Autowired
- 自动按照类型注入。当使用注解注入属性时,set 方法可以省略。它只能注入其他 bean 类型。当有多个类型匹配时,使用要注入的对象变量名称作为 bean 的 id,在 spring 容器查找,找到了也可以注入成功。找不到就报错。
@Qualifier
- 在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和@Autowire 一起使用;但是给方法参数注入时,可以独立使用。
- value:指定 bean 的 id。
@Resource
- 直接按照 Bean 的 id 注入。它也只能注入其他 bean 类型。
- name:指定 bean 的 id。
@Value
- 注入基本数据类型和 String 类型数据的
- value:用于指定值
2.3 用于改变作用范围的
@Scope
- 指定 bean 的作用范围。
- value:指定范围的值。取值:singleton prototype request session globalsession
2.4 和生命周期相关的
@PostConstruct
- 用于指定初始化方法。
@PreDestroy
- 用于指定销毁方法。
2.5 关于 Spring 注解和 XML 的选择问题
- 注解的优势:配置简单,维护方便(我们找到类,就相当于找到了对应的配置)。
- XML 的优势:修改时,不用改源码。不涉及重新编译和部署
基于XML配置 | 基于注解配置 | |
---|---|---|
Bean定义 | <bean id="…“ class=”…"/> | @Component 衍生类@Repository @Service @Controller |
Bean名称 | 通过id或name 指定 | @Component(“person”) |
Bean注入 | <property>或者 通过p名命空间 | @Autowired按类型注入 @Qualifier按名称注入 |
生命过程、 Bean作用范围 | init-method destroy-method 范围scope属性 | @PostConstruct初始化 @PreDestroy销毁 @Scope设置作用范围 |
适合场景 | Bean来自第三 方,使用其他 | Bean的实现类由用户自己 开发 |
基于注解的 spring IoC 配置中,bean 对象的特点和基于 XML 配置是一模一样的。
3. spring 的纯注解配置
3.1 待改造的问题
我们发现,之所以我们现在离不开 xml 配置文件,是因为我们有一句很关键的配置:
<!-- 告知spring框架在,读取配置文件,创建容器时,扫描注解,依据注解创建对象,并存入容器中 -->
<context:component-scan base-package="org.woster"></context:component-scan>
如果他要也能用注解配置,那么我们就离脱离 xml 文件又进了一步。
另外,数据源和 JdbcTemplate 的配置也需要靠注解来实现。
<!-- 配置 dbAssit -->
<bean id="dbAssit" class="org.woster.dbassit.DBAssit">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///spring_day02"></property>
<property name="user" value="root"></property>
<property name="password" value="1234"></property>
</bean>
3.2 新注解说明
@Configuration
- 用于指定当前类是一个 spring 配置类,当创建容器时会从该类上加载注解。获取容器时需要使用AnnotationApplicationContext(有@Configuration 注解的类.class)。
- value:用于指定配置类的字节码
@Configuration
public class SpringConfiguration {
}
@ComponentScan
- 用于指定 spring 在初始化容器时要扫描的包。作用和在 spring 的 xml 配置文件中的:<context:component-scan base-package=“org.woster”/>是一样的。
- basePackages:用于指定要扫描的包。和该注解中的 value 属性作用一样。
@Configuration
@ComponentScan("org.woster")
public class SpringConfiguration {
}
@Bean
- 该注解只能写在方法上,表明使用此方法创建一个对象,并且放入 spring 容器。
- name:给当前@Bean 注解方法创建的对象指定一个名称(即 bean 的 id)。
public class JdbcConfig {
/**
* 创建一个数据源,并存入 spring 容器中
* @return
*/
@Bean(name="dataSource")
public DataSource createDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setUser("root");
ds.setPassword("1234");
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql:///test");
return ds;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 创建一个 DBAssit,并且也存入 spring 容器中
* @param dataSource
* @return
*/
@Bean(name="dbAssit")
public DBAssit createDBAssit(DataSource dataSource) {
return new DBAssit(dataSource);
}
}
@PropertySource
- 用于加载.properties 文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到properties 配置文件中,就可以使用此注解指定 properties 配置文件的位置。
- value[]:用于指定 properties 文件位置。如果是在类路径下,需要写上 classpath:
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 容器中
* @return
*/
@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);
}
}
}
jdbc.properties 文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=1234
@Import
- 用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration 注解。当然,写上也没问题。
- value[]:用于指定其他配置类的字节码。
@Configuration
@ComponentScan(basePackages = "org.woster.spring")
@Import({ JdbcConfig.class})
public class SpringConfiguration {
}
@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig{
}
3.3 通过注解获取容器
4. Spring 整合 Junit
4.1 测试类中的问题和解决思路
问题
在测试类中,每个测试方法都有以下两行代码:
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。
解决思路分析
针对上述问题,我们需要的是程序能自动帮我们创建容器。一旦程序能自动为我们创建 spring 容器,我们就无须手动创建了,问题也就解决了
我们都知道,junit 单元测试的原理(在 web 阶段课程中讲过),但显然,junit 是无法实现的,因为它自己都无法知晓我们是否使用了 spring 框架,更不用说帮我们创建 spring 容器了。不过好在,junit 给我们暴露了一个注解,可以让我们替换掉它的运行器。
这时,我们需要依靠 spring 框架,因为它提供了一个运行器,可以读取配置文件(或注解)来创建容器。我们只需要告诉它配置文件在哪就行了。
4.2 配置步骤
第一步:导入整合 junit 的必备 jar 坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
第二步:使用@RunWith 注解替换原有运行器
@RunWith(SpringJUnit4ClassRunner.class)
public class AccountServiceTest {
}
第三步:使用@ContextConfiguration 指定 spring 配置文件的位置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
}
@ContextConfiguration 注解:
- locations 属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath:表明
- classes 属性:用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置。
第四步:使用@Autowired 给测试类中的变量注入数据
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
@Autowired
private IAccountService as ;
}