环境搭建
先导入坐标 pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
</dependencies>
配置文件
<?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
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在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为
context名称空间和约束中-->
<context:component-scan base-package="cn.junko"></context:component-scan>
</beans>
Spring中IOC的常用注解
- 用于创建对象
@Component
用于把当前对象存入Spring容器中。该注解中有一个value属性 对应 <bean>
标签
value属性:用于指定bean的id,不写默认值是当前类名,且首字母改小写。
@Controller、@Service、@Repository
这三个注解作用与@Component一样 ,是Spring框架提供明确三层使用的注解,使三层对象更加清晰,一般用于场景(表现层)(业务层)(持久层)
- 用于注入数据
@Autowired
自动按照类型注入,只要容器中有唯一一个bean对象类型和要注入的变量类型匹配,直接注入成功。<bean
>标签的<property>
标签
如果IOC容器中有多个类型匹配时,会去找key上是否有对应的名字,否则报错。
@Qualifier
与@Autowired
配合使用,在按照类注入的基础上再按照名称注入。在给类成员注入时不能单独使用,给方法注入可以
value属性:用于指定注入bean的id。
@Resource
直接按照bean的id注入,可独立使用
name属性:用于指定bean的id
上面三个注解只能注入其他bean类型的数据,而基本类型和String类型无法使用,集合类型只能通过XML注入
@Value
用于注入基本类型和String类型的数据
value属性:用于指定数据的值,可以使用Spring中的SpEL(spring的EL表达式)
- 用于改变作用范围
Scope
指定bean的作用范围
value属性:指定范围的取值,常用取值singleton、prototype
- 生命周期相关
PreDestory
指定销毁方法
PostConstruct
指定初始化方法
案例使用XML方式和注解方式实现单表CRUD操作(DBUtils)
环境准备
pom.xml
<?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>cn.junko</groupId>
<artifactId>spring_study</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</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.10</version>
</dependency>
</dependencies>
</project>
账户实体类
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
//getter setter tostring
}
DAO
/**
* 账户的持久层接口
*/
public interface IAccountDao {
List<Account> findAllAccount();
Account findAccountById(Integer aid);
void saveAccount(Account account);
void updateAccount(Account account);
void deleteAccount(Integer aid);
}
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl implements IAccountDao{
private QueryRunner runner;
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
public List<Account> findAllAccount() {
try {
return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Account findAccountById(Integer aid) {
try {
return runner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void saveAccount(Account account) {
try {
runner.update("insert into account (name,money) values (?,?)",account.getName(),account.getMoney());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void updateAccount(Account account) {
try {
runner.update("update account set name = ?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void deleteAccount(Integer aid) {
try {
runner.update("delete from account where id = ?",aid);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
Service
/**
* 账户业务层的接口
*/
public interface IAccountService {
List<Account> findAllAccount();
Account findAccountById(Integer aid);
void saveAccount(Account account);
void updateAccount(Account account);
void deleteAccount(Integer aid);
}
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
public Account findAccountById(Integer aid) {
return accountDao.findAccountById(aid);
}
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
public void deleteAccount(Integer aid) {
accountDao.deleteAccount(aid);
}
}
配置文件bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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
">
<!--配置service-->
<bean id="accountService" class="cn.junko.service.impl.AccountServiceImpl">
<!--注入dao-->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置dao对象-->
<bean id="accountDao" class="cn.junko.dao.impl.AccountDaoImpl">
<!--注入QueryRunner-->
<property name="runner" ref="runner"></property>
</bean>
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!--注入数据源-->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</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://localhost:3306/eesy"></property>
<property name="user" value="root"></property>
<property name="password" value="12345678"></property>
</bean>
</beans>
测试
public class AccountServiceTest {
IAccountService as;
@Before
public void init(){
//获取容器
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
//得到业务层对象
as = ac.getBean("accountService", IAccountService.class);
}
@Test
public void testFindAll(){
/* //获取容器
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
//得到业务层对象
IAccountService as = ac.getBean("accountService", IAccountService.class);*/
//执行方法
List<Account> accounts=as.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
@Test
public void testFindOne(){
Account accountById = as.findAccountById(1);
System.out.println(accountById);
}
改造基于注解的IOC,使用纯注解实现
我们发现,之所以我们现在离不开 xml 配置文件,是因为我们有一句很关键的配置:
<!-- 告知spring框架在,读取配置文件,创建容器时,扫描注解,依据注解创建对象,并存入容器中 -->
<context:component-scan base-package="com.itheima"></context:component-scan>
如果他要也能用注解配置,那么我们就离脱离 xml 文件又进了一步。
@Configuration
作用: 用于指定当前类是一个 spring 配置类,当创建容器时会从该类上加载注解。获取容器时需要使用AnnotationApplicationContext(有@Configuration 注解的类.class)。
属性: value:用于指定配置类的字节码.
@ComponentScan
作用: 用于指定 spring 在初始化容器时要扫描的包。作用和在 spring 的 xml 配置文件中的:
<context:component-scan base-package="com.itheima"/>
是一样的。
属性: basePackages:用于指定要扫描的包。和该注解中的 value 属性作用一样。
/**
* spring 的配置类,相当于 bean.xml 文件
*/
@Configuration
@ComponentScan("cn.junko")
public class SpringConfiguration {
}
@Bean
作用:
该注解只能写在方法上,表明使用此方法创建一个对象,并且放入 spring 容器。与@Autowired
注解作用一样
属性:
name:给当前@Bean 注解方法创建的对象指定一个名称(即 bean 的 id)。