Spring框架
两大核心:IOC AOP
此篇将要讲解第一个核心IOC的用注解方法的配置
第二天:
基于注解的IOC配置
第一天中提到的,在xml配置文件中创建对象:
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl" scope="" init-method="" destroy-method="">
<property name="" value=""ref=""></property>
</bean>
用注解方式(对应上述xml方法)有以下四类注解:
1 用于创建对象的:@Component @Controller @Service @Repository
2 用于注入数据的:@Autowired @Qualifier @Resource @Value
3 用于改变作用范围的:@Scope
4 与生命周期相关的:@PostConstruct @PreDestroy
- 1 用于创建对象的:作用同xml中标签
@Component:
作用:用于把当前对象存入spring容器中
属性:value:用于指定bean的id。即用容器(Map<key,value>形式存储)查找对象创建时getBean的对象的key就是此处注解的value值
@Component(value="")(写在public class之前)其中value可省略。
当我们不写此属性时,默认value值为当前类名(首字母小写)
@Controller:一般用于表现层
@Service: 一般用于业务层
@Repository:一般用于持久层
以上三个注解的作用和属性与@Component一致。他们是Spring框架为我们提供明确的三层使用的注解,使三层对象更加清晰。
2 用于注入数据的:作用同xml中标签
@Autowired:
作用:自动按照类型注入,只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功。
若没有可匹配的,则报错;
若有多个匹配时,则在匹配的几个对象的范围中再匹配变量名和这些对象名(对象名就是Map的key,也即 @Component等4个注解的value)是否一致
若匹配(此时只可能唯一匹配)则注入成功,若无匹配则报错。
(变量名一定要和对象名一致->在实际开发并不很合理->@Qualifier解决此缺陷)
出现位置:可以是变量上,也可以是方法上
细节:在使用注解注入时,set方法就不是必须的了@Qualifier:
作用:再按照类中注入的基础上再按照名称注入,他在给类成员注入时不能单独使用(要和@Autowired组合在一起),但在给方法参数注入时可以单独使用。
属性:value:用于指定注入bean的id@Resource:
作用:直接按照bean的id注入,可以独立使用(解决上面两个都要在的不合理之处)
属性:name:用于指定注入bean的id以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现。另外,集合类型的注入只能通过xml来实现。
@Value:
作用:用于注入基本类型和String类型的数据
属性:value:用于指定数据的值。它可以使用spring中的SpEL(spring中的EL表达式)
SpEL的写法:${表达式}
- 3 用于改变作用范围的:作用同xml中scope属性
@Scope
作用:用于指定bean的作用范围
属性:value:指定范围的取值(singleton单例【默认】 prototype多例)
- 4 与生命周期相关的:作用同xml中init-method和destroy-method属性
@PostConstruct:初始化
@PreDestroy:销毁
以下是xml+注解的方式:
pom导坐标:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>day02_eesy_04account_annoioc_withoutXML</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
</dependencies>
</project>
业务层实现类AccountServiceImpl.java:
package com.itheima.service.impl;
import com.itheima.service.IAccountService;
import com.itheima.dao.IAccountDao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
//账户业务层实现类
@Service
@Scope("singleton")
public class AccountServiceImpl implements IAccountService {
// @Autowired
// @Qualifier(value = "accountDao1")
@Resource(name = "accountDao1")
private IAccountDao acc = null;
@PostConstruct
public void init(){
System.out.println("初始化");
}
@PreDestroy
public void destroy(){
System.out.println("销毁");
}
public void saveAccount(){
acc.saveAccount();
}
}
【关键一步】
原来的配置文件bean.xml并不是全都删掉,而是:
1.导入依赖:xmlns:context
2.扫包:如果不扫,在servlet中getBean永远get不到【报错会说找不到】,添加这一行,框架会知道要去什么范围内的文件里查找所传进去的key值。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--告知spring在创建容器时要扫描的包,配置所需的标签不是在beans的约束中,而是在一个名称为context名称空间和约束中-->
<context:component-scan base-package="com.itheima"></context:component-scan>
</beans>
以下过渡到纯注解:
如果想要全部用注解,完全删掉xml配置文件,也是可以实现的 -> 创建一个父配置类SpringConfiguration以及其他子配置类来代替bean.xml的功能。
spring中的新注释:
@Configuration
* 作用:当前类是一个配置类
* 细节:当配置类作为AnnotationConfigurationContext对象创建的参数时,该注解可以不写
* AccountServiceTest.java中
* ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
@ComponentScan
* 作用:用于通过注解指定spring在创建容器时要扫描的包
* 等同于xml中的扫包:<context:component-scan base-package="com.itheima"></context:component-scan>
* 属性:value:和basePackages的作用一致
@Bean
* 作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
* 属性:name:用于指定bean的id。当不写时默认值是当前方法的名称
* 细节:当使用注解配置方法时,若方法有参数,spring框架会去容器中查找有无可用的bean对象。
* 查找方法同@Autowired
@Import
* 作用:用于导入其他的配置类
* 属性:value:用于指定其他配置类的字节码
* 有@Import注解的类是主/父配置类
@PropertySource
* 作用:用于指定properties文件的位置
* 属性:value:指定文件的名称和路径
* 关键字:classpath:表示类路径下
关于父子配置类的关联:
方法1:可以在父配置类@ComponentScan后加上所有配置类所在的包
方法2:可以在表现层的获取容器那一步参数再加上子配置类
方法3:在父配置类中加上注解:@Import(子配置类名.class) ->最方便的方法
父配置类:SpringConfiguration.java
package config;
import org.springframework.context.annotation.*;
//@Configuration
@ComponentScan(basePackages = "com.itheima")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
}
子配置类:JdbcConfig.java
package config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;
//和spring连接数据库相关的配置(子配置类)
//@Configuration
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对象 @Bean负责把创建出的对象放入容器中
* 对应于原来xml配置文件中的:
* <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!--注入数据源(因为没有set方法,所以采用构造函数的方法)-->
<constructor-arg name="ds" ref="dataresource"></constructor-arg>
</bean>
*/
@Bean(name = "runner")
@Scope("prototype")
//当有多个数据源的时候可以在参数部分用@Qualifier("@Bean的name")指定具体哪个数据源
public QueryRunner createQueryRunner(@Qualifier("ds1") DataSource datasource){
return new QueryRunner(datasource);
}
/*创建数据源对象 @Bean负责把创建出的对象放入容器中
* 对应于原来xml配置文件中的:
* <bean id="dataresource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--注入连接数据库的必备信息-->
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<property name="jdbcUrl" value=""></property>
<property name="user" value=""></property>
<property name="password" value=""></property>
</bean>
*/
@Bean(name = "ds1")
public DataSource createDataSource(){
ComboPooledDataSource ds = new ComboPooledDataSource();
try {
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
} catch (Exception e){
throw new RuntimeException(e);
}
}
//为了演示多数据源下@Qualifier注解的使用而加的第二个数据源
@Bean(name = "ds2")
public DataSource createDataSource1(){
ComboPooledDataSource ds = new ComboPooledDataSource();
try {
ds.setDriverClass(driver);
ds.setJdbcUrl("jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8");
ds.setUser(username);
ds.setPassword(password);
return ds;
} catch (Exception e){
throw new RuntimeException(e);
}
}
}
为了使数据源信息修改更灵活:JdbcConfig.properties
此时测试类沿用第一天的照常运行,只需要将获取容器那步的类名以及接口改掉即可。
但是仍存在问题:每个测试方法下都有获取容器、获得对象这两步完全一样的代码,能否消除此处冗余?
//1.获取容器
//ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); xml方法用此接口
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class); //注解方法要改接口
//2.得到业务层对象
IAccountService as = ac.getBean("accountService",IAccountService.class);
提取出获取对象的变量。
@Autowired
private IAccountService as;
引入新的注解:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class) 表示获取容器(如果是用bean.xml,则 location = “bean.xml”) 作用相当于下面代码:
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
测试类AccountServiceTest.java最终:
package com.itheima.test;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import config.SpringConfiguration;
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;
import java.util.List;
//使用Junit单元测试:测试配置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private IAccountService as;
@Test
public void testFindAll(){
List<Account> accounts = as.findAllAccount();
for(Account account:accounts){
System.out.println(account);
}
}
@Test
public void testFindOne(){
Account account = as.findAccountById(1);
System.out.println(account);
}
@Test
public void testSave(){
Account account = new Account();
account.setName("ddd");
account.setMoney(12345f);
as.saveAccount(account);
}
@Test
public void testUpdate(){
Account account = as.findAccountById(4);
account.setMoney(1000f);
as.updateAccount(account);
}
@Test
public void testDelete(){
as.deleteAccount(5);
}
}
结束!
纯注解要很注重细节,纯xml写起来也挺麻烦。xml+注解混合用才是王道!