1.使用基于注解的spring配置的话,xml文件中的开头配置需要加上含有context的。在下面这个链接中搜索"xmlns:context"即可得到这段代码。将其复制到bean.xml配置文件中。https://docs.spring.io/spring/docs/5.1.8.RELEASE/spring-framework-reference/core.html#spring-core
<!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为
context名称空间和约束中-->
<context:component-scan base-package="com.itheima"></context:component-scan>
2。一些注解的使用:
@Autowired:自动按照类型注入,set方法可以省略,只能注入其他bean类型,当有多个类型匹配时,使用要注入的对象变量名作为bean对象的id。
/**
* 账户的业务层实现类
*
* 曾经XML的配置:
* <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
* scope="" init-method="" destroy-method="">
* <property name="" value="" | ref=""></property>
* </bean>
*
* 用于创建对象的
* 他们的作用就和在XML配置文件中编写一个<bean>标签实现的功能是一样的
* @Component:
* 作用:用于把当前类对象存入spring容器中
* 属性:
* value:用于制定bean的id。当我们不写是,他的默认值是当前雷鸣,且首字母该小写。
* Controller:一般用在表现层
* Service:一般用在业务层
* Repository:一般用在持久层
* 以上三个注解他们的作用和属性与Component是一模一样的,它们三个是spring框架为我们提供的三层
* 使用的注解,使我们的三层对象更加清晰
* 用于注入数据的
* 他们的作用就和在xml配置文件中的bean标签中写一个<property>标签的作用是一样的
* Autowired:
* 作用:自动按照类型注入,主要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
* 如果IOC容器中没有任何bean的类型和要注入的变量类型匹配,就会报错
* 如果有多个类型匹配时:
* 书写位置:可以是变量上,也可以是方法上
*
* 在使用注解注入时,set方法就不是必须的了
* Qualifier:
* 在按照类中注入的基础之上再按照名称注入,他在给类成员注入时不能单独使用,但是在给方法参数注入时可以。
* 属性:
* value:用于制定注入bean的id
*
* Resource:
* 作用:直接按照bean的id注入,可以独立使用
* 属性:
* name:用于制定bean的id
*
* 以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现。
* 另外,集合类型的注入只能通过XML来实现
*
*
* Value:
* 作用:用于注入基本类型和String类型的数据
* 属性
* value:用于制定数据的值,它可以使用spring中的spel(spring中的el表达式)
* SpEL的写法:${表达式}
* 用于改变作用范围的
* 他们的作用就和在bean标签中使用scope属性实现的功能是一样的
* Scope
* 作用:用于指定bean的作用范围
* 属性:
* value 指定范围的取值,常用取值:singleton protorype 分别对应单例和多例
* 和生命周期相关 了解
* 他们的作用就和在bean标签中使用init-method和destroy-methode的作用是一样的
* PreDestory
* 用于指定销毁方法
* PostConstruct
初始化方法
*/
例子:
//@Service("accountService")
//@Scope("prototype")
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
// @Autowired
// @Qualifier("accountDao2")
@Resource(name = "accountDao2")
private IAccountDao accountDao;
@PostConstruct
public void init(){
System.out.println("初始化方法执行了");
}
@PreDestroy
public void destroy(){
System.out.println("销毁方法执行了");
}
public void saveAccount(){
accountDao.saveAccount();
}
}
案例:使用xml和注解的方式实现单标crud
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"
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在创建容器时要扫描的包-->
<context:component-scan base-package="com.itheima"></context:component-scan>
<!--配置QueryRunner-->
<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/book"></property>
<property name="user" value="root"></property>
<property name="password" value="123"></property>
</bean>
</beans>
持久层:
/**
* 账户的持久层实现类
*/
@Repository("accontDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private QueryRunner runner;
@Override
public List<Account> findAllAccount() {
try {
return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Account findAccountById(Integer accountId) {
try {
return runner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),accountId);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void saveAccount(Account account) {
try {
runner.update("insert into account(name,money) values(?,?) ",account.getName(),account.getMoney());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void updateAccount(Account account) {
try {
runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void deleteAccount(Integer accountId) {
try {
runner.update("delete from account where id=?",accountId);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
业务层:
/**
* 账户的业务层实现类
*/
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
@Override
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
@Override
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
@Override
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
@Override
public void deleteAccount(Integer accountId) {
accountDao.deleteAccount(accountId);
}
}
测试类:
/**
* 使用Junit单元测试,测试我们的配置
*/
public class AccountServiceTest {
@Test
public void testFindAll() {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
IAccountService as = ac.getBean("accountService", IAccountService.class);
//3.执行方法
List<Account> accounts = as.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
@Test
public void testFindOne() {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
IAccountService as = ac.getBean("accountService", IAccountService.class);
//3.执行方法
Account account = as.findAccountById(1);
System.out.println(account);
}
@Test
public void testSave() {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
IAccountService as = ac.getBean("accountService", IAccountService.class);
Account account = new Account();
account.setName("李晓威");
account.setMoney(999999999F);
as.saveAccount(account);
}
@Test
public void testUpdate() {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
IAccountService as = ac.getBean("accountService", IAccountService.class);
Account account = as.findAccountById(4);
account.setMoney(5656565656565f);
as.updateAccount(account);
}
@Test
public void testDelete() {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
IAccountService as = ac.getBean("accountService", IAccountService.class);
as.deleteAccount(3);
}
}
上述的案例没有完全抛弃xml文件,所以一下进行改进。
使用一个SpringConfiguration类来代替xml文件。
package config;
/**
* @author 李晓威
* @create 2021-06-02-16:42
*/
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;
/**
* 该类是一个配置类,该类的作用适合bean.xml是一样的
* spring中的新注解:
* Configuration:
* 作用:指定当前类是一个配置类
* ComponentScan
* 作用:用于通过注解指定spring在创建容器时要扫描的包
* 属性:
* value:他和basePackages的作用是一样的,都适用于指定创建容器时需要扫描的包
* 我们使用此注解就等同于在xml中配置了:
* <context:component-scan base-package="com.itheima"></context:component-scan>
* Bean:
* 作用:用于把当前方法的返回值作为bean对象存入spring的IOC容器中
* 属性:
* name:用于指定bean的id,当不写时,默认值是当前方法的名称
* 细节:
* 当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象
* 查找的方式和Autowired注解的作用是一样的
*
*/
@Configuration
@ComponentScan("com.itheima")
public class SpringConfiguration {
/**
*用于创建一个QueryRunner对象
*/
@Bean(name = "runner")
@Scope("prototype")
public QueryRunner createQueryRunner(DataSource dataSource) {
return new QueryRunner(dataSource);
}
/**
* 创建数据源对象
* @return
*/
@Bean(name="dataSource")
public DataSource createDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/book");
ds.setUser("root");
ds.setPassword("123");
return ds;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
单纯使用注解的方式实现spring的时候,获取ApplicationContext容器的方式也要改变:
package com.itheima.test;
/**
* @author 李晓威
* @create 2021-06-01-22:49
*/
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import config.SpringConfiguration;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
/**
* 使用Junit单元测试,测试我们的配置
*/
public class AccountServiceTest {
@Test
public void testFindAll() {
//1.获取容器
// ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//2.得到业务层对象
IAccountService as = ac.getBean("accountService", IAccountService.class);
//3.执行方法
List<Account> accounts = as.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
@Test
public void testFindOne() {
//1.获取容器
//ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//2.得到业务层对象
IAccountService as = ac.getBean("accountService", IAccountService.class);
//3.执行方法
Account account = as.findAccountById(1);
System.out.println(account);
}
@Test
public void testSave() {
//1.获取容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//2.得到业务层对象
IAccountService as = ac.getBean("accountService", IAccountService.class);
Account account = new Account();
account.setName("李晓威");
account.setMoney(9555999F);
as.saveAccount(account);
}
@Test
public void testUpdate() {
//1.获取容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//2.得到业务层对象
IAccountService as = ac.getBean("accountService", IAccountService.class);
Account account = as.findAccountById(4);
account.setMoney(5656565656565f);
as.updateAccount(account);
}
@Test
public void testDelete() {
//1.获取容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//2.得到业务层对象
IAccountService as = ac.getBean("accountService", IAccountService.class);
as.deleteAccount(3);
}
}
此外还在SpringConfiguration类中给getQueryRunner方法添加了多例的注解。测试如下:
package com.itheima.test;
/**
* @author 李晓威
* @create 2021-06-02-19:20
*/
import config.SpringConfiguration;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* 测试queryrunner是否单例
*/
public class QueryRunnerTest {
@Test
public void testQueryRunner() {
//1.获取容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//2.获取queryrunner对象
QueryRunner runner = ac.getBean("runner", QueryRunner.class);
QueryRunner runner2 = ac.getBean("runner", QueryRunner.class);
System.out.println(runner ==runner2);
}
}
针对以上的springConfig配置类还可以做出改进,可以将获取连接的操作移植出来,重新编写一个配置类.
新的springConfig配置类
package config;
import org.springframework.context.annotation.*;
/**
* 该类是一个配置类,该类的作用适合bean.xml是一样的
* spring中的新注解:
* Configuration:
* 作用:指定当前类是一个配置类
* 细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写
* ComponentScan
* 作用:用于通过注解指定spring在创建容器时要扫描的包
* 属性:
* value:他和basePackages的作用是一样的,都适用于指定创建容器时需要扫描的包
* 我们使用此注解就等同于在xml中配置了:
* <context:component-scan base-package="com.itheima"></context:component-scan>
* Bean:
* 作用:用于把当前方法的返回值作为bean对象存入spring的IOC容器中
* 属性:
* name:用于指定bean的id,当不写时,默认值是当前方法的名称
* 细节:
* 当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象
* 查找的方式和Autowired注解的作用是一样的
* Import:
* 作用:用于导入其他的配置类
* 属性:
* value:用于制定其他配置类的字节码
* 当我们使用Import的注解之后,有import注解的类就是父配置类,而导入的都是子配置类。
* PropertySource
* 用于制定properties文件的位置
* 属性:
* value:指定文件的名称和路径
* 关键字:classpath,表示类路径下
*/
//@Configuration
@ComponentScan("com.itheima")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
}
从springConfig配置类中分离出来的jdbcConfig类:
package config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;
/**
* 和spring连接数据库相关的配置类
*/
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(name = "runner")
@Scope("prototype")
public QueryRunner createQueryRunner(DataSource dataSource) {
return new QueryRunner(dataSource);
}
/**
* 创建数据源对象
* @return
*/
@Bean(name="ds2")
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);
}
}
@Bean(name="ds1")
public DataSource createDataSource2() {
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);
}
}
}
在resources包下的配置文件jdbcConfig.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/book
jdbc.username=root
jdbc.password=123