Spring注解
基础配置
- DAO层的接口
package com.bdit.dao;
public interface AccountDao {
public void saveAccount();
}
- DAO接口的实现类
package com.bdit.dao.impl;
import com.bdit.dao.AccountDao;
import org.springframework.stereotype.Component;
public class AccountDaoImpl implements AccountDao {
@Override
public void saveAccount() {
}
public AccountDaoImpl(){
System.out.println("DAO层 ==");
}
}
- 业务层接口
package com.bdit.service;
import org.springframework.stereotype.Component;
@Component
public interface AccountService {
void saveAcccount();
}
- 业务层实现类
package com.bdit.service.impl;
import com.bdit.dao.AccountDao;
import com.bdit.service.AccountService;
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public AccountServiceImpl(){
System.out.println("============= 业务层默认的构造方法 ==========");
}
@Override
public void saveAcccount() {
accountDao.saveAccount();
}
}
- 测试类
public class TextAccount {
}
- beans.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
">
</beans>
1、用于创建对象
用于创建对象的(标记于业务层)
作用就和在xml配置文件中的 <bean></bean> 标签实现的功能是一样的
@Component
作用:用于把当前类对象存入Spring容器(key=value形式存在)中
属性:
value:1、用于指定bean的id,当未在 @Component(value = "")中定义是,value就是当前类名,且首字母小写
2、如果只有一个则value可以省略直接是:@Component(”accountService“)
@Controller(一般用在表现层)
@Service(一般用在业务层)
@Repository(一般用在持久层)
以上三个注解(@Controller @Service @Repository) 作用和属性与Component作用、属性一模一样
这三个是Spring框架提供的明确三层使用的注解,使三层对象更加清晰
应用:
- 在 package com.bdit.service.impl.AccountServiceImpl中加入
@Component //将 AccountServiceImpl 类反射创建一个对象存入Spring容器中
public class AccountServiceImpl implements AccountService {}
- 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
https://www.springframework.org/schema/context/spring-context.xsd
">
<!--告诉Spring在创建容器时,就要扫描的包,实现其里面的注解
配置的标签不在bean中而是在 context 名称空间和约束中 -->
<context:component-scan base-package="com.bdit"/>
<!--在此时的xml中可以是最原始的状态,也可以是这种-->
</beans>
- 测试类中
@Test
public void text01(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
AccountService a = context.getBean("accountServiceImpl",AccountService.class);
System.out.println(a);
}
2、用于注入数据
用于注入数据
作用和xml配置文件中的bean标签内的<property></property> 标签作用一致
@Autowired:
作用:自动按照类型注入,只要容器中有唯一一个bean对象类型和要注入的变量类型匹配,就可以注入成功
如果IOC容器中没有任何bean类型和要注入的变量匹配,则报错
如果IOC容器中有多个类型匹配时
先用过数据类型去匹配,这是会匹配到多个,再通过变量名称确定唯一
@Autowired
private AccountDao accountDao02 = null;
访问修饰符 数据类型 变量名称 数据类型
位置:可以实变量上,也可以是方法上
注意:在使用注解注入的时,set方法不是必须的了
Spring的IOC容器是一个 MAP( key(String) value(Object) ) 结构
@Qualifier:
作用:在按照类中注入的基础之上再按照名称注入,再给类成员注入的时候不能单独使用,如果通过构造方法注入,该注解则需
要放在构造方法参数的前面
属性:
value:用于指定注入的ID
@Resource:
作用:直接按照bean的id注入可以独立使用,不能用在构造方法上,此时类中也不要提供有参数的构造方法。
属性:
name:用于指定bean的id
type:用于指定注入的class 例如: @Resource(type = AccountDaoImpl.class)
以上只能注入其它bean类型的数据,基本数据类型、String类型无法使用上述注解完成,集合的注入只能通过xml来实现
@Value
作用:用于注入基本上类型和String类型的数据
属性:
value:用于指定数据的值,可以使用spring中的spel(el表达式)
spel写法:${表达式}
注入总结
// 第一种:
// @Autowired //作用:自动按照类型注入
// //accountDao与 DAO层实现类 AccountDaoImpl 中value值一致
// private AccountDao accountDao02;//需要定义注入的变量名称
// 第二种
// @Autowired
// @Qualifier("accountDao02")
// 注意:使用 @Qualifier 放在构造方法时,最好把 @Autowired 放在构造方法之上
//
// 例如:
// private AccountDao accountDao;
// @Autowired
// public AccountServiceImpl(@Qualifier(value = "accountDao02") AccountDao accountDao) {
// this.accountDao=accountDao;
// System.out.println("===================构造方法");
// }
// 第三种
// @Resource:(name="accountDao02")
// private AccountDao accountDao;
// 或者
// @Resource(type = AccountDaoImpl.class)
// private AccountDao accountDao;
//
// 注意:
// private AccountDao accountDao;
// @Autowired
// @Resource(name = "accountDao02" )
// @Resource(type = ACCountDaoImpl02.class )
// public void setAccountDao(AccountDao accountDao) {
// System.out.println("===========SetAccountDao");
// this.accountDao = accountDao;
// }
- 业务层接口实现类
package com.bdit.service.impl;
import com.bdit.dao.AccountDao;
import com.bdit.dao.impl.ACCountDaoImpl02;
import com.bdit.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Component //将 AccountServiceImpl 类反射创建一个对象存入Spring容器中
public class AccountServiceImpl implements AccountService {
//第一种(其余都可不变)
@Autowired
private AccountDao accountDao02;
//第二种(方式一)
@Autowired
@Qualifier("accountDao02")
public AccountServiceImpl(AccountDao accountDao) {
this.accountDao=accountDao;
System.out.println("===================AccountServiceImpl的构造方法,不是dao的构造方法==================");
}
//第二种(方式二)
@Autowired
public AccountServiceImpl(@Qualifier("accountDao02")AccountDao accountDao) {
this.accountDao=accountDao;
System.out.println("===================AccountServiceImpl的构造方法,不是dao的构造方法==================");
}
//第三种
@Resource(name = "accountDao02" )//(方式一)
@Resource(type = ACCountDaoImpl02.class )//(方式二)
public void setAccountDao(AccountDao accountDao) {
System.out.println("===========SetAccountDao");
this.accountDao = accountDao;
}
public AccountServiceImpl(){
System.out.println("============= 业务层默认的构造方法 ==========");
}
@Override
public void saveAcccount() {
accountDao.saveAccount();
System.out.println("============ AccountServiceImpl 中实现 AccountService.class 的 saveAcccount() ===========");
}
}
-
DAO层实现类
- 实现两个实现类,数据类型相同,但value值不一样
第一个
package com.bdit.dao.impl;
import com.bdit.dao.AccountDao;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
/**
* @Package: com.bdit.dao.impl
* @ClassName: AccountDaoImpl
* @Author: Ling
* @Date: 2020/11/13 7:00
* @Description:
*/
@Repository("accountDao01")
public class AccountDaoImpl implements AccountDao {
@Override
public void saveAccount() {
System.out.println("============ AccountDaoImpl 中实现 AccountDao.class 的 saveAcccount() ===========");
}
public AccountDaoImpl(){
System.out.println("============ DAO层 AccountDaoImpl默认的构造方法 ============");
}
}
第二个
package com.bdit.dao.impl;
import com.bdit.dao.AccountDao;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
/**
* @Package: com.bdit.dao.impl
* @ClassName: ACCountDaoImpl02
* @Author: Ling
* @Date: 2020/11/16 13:17
* @Description:
*/
@Repository("accountDao02")
public class ACCountDaoImpl02 implements AccountDao {
@Override
public void saveAccount() {
System.out.println("ACCountDaoImpl02");
}
}
- 测试类
public class TextAccount {
@Test
public void text03(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
AccountService a = context.getBean("accountServiceImpl",AccountService.class);
a.saveAcccount();
}
}
3、用于改变作用范围
用于改变作用范围的
作用:和bean标签中的scope属性实现的功能是一样的
Scope
作用:指定bean的作用范围
属性:
value:指定范围的取值,常用取值:singleton单例 prototype多例(默认是单例)
例如:
@Component
//@Scope("prototype") 多例
public class AccountServiceImpl implements AccountService { }
- 业务层实现类
@Component
@Scope("prototype")//默认不写为单例
public class AccountServiceImpl implements AccountService {其余不变}
- 测试类
public class TextAccount {
@Test
public void text04(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
AccountService a = context.getBean("accountServiceImpl",AccountService.class);
a.saveAcccount();
}
}
4、用于改变生命周期
用于生命周期的
作用:与bean标签中的 init-method 和 destroy-methode 的作用是一样的
@PreDestroy:作用:用于指定销毁方法
@PostConstruct:作用:用于指定初始化方法
- 业务层实现类
package com.bdit.service.impl;
import com.bdit.dao.AccountDao;
import com.bdit.dao.impl.ACCountDaoImpl02;
import com.bdit.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
@Component
//@Scope("prototype")
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
@Autowired
@Resource(type = ACCountDaoImpl02.class )
public void setAccountDao(AccountDao accountDao) {
System.out.println("===========SetAccountDao");
this.accountDao = accountDao;
}
public AccountServiceImpl(){
System.out.println("============= 业务层默认的构造方法 ==========");
}
@Override
public void saveAcccount() {
accountDao.saveAccount();
System.out.println("============ AccountServiceImpl 中实现 AccountService.class 的 saveAcccount() ===========");
}
@PostConstruct
public void Accountinit(){
System.out.println("======================== 初始化方法init ========================");
}
@PreDestroy
public void Accountdestory(){
System.out.println("======================== 销毁方法 ========================");
}
}
- 测试类
public class TextAccount {
@Test
public void text04(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
AccountService a = context.getBean("accountServiceImpl",AccountService.class);
a.saveAcccount();
}
}
5、IOC综合案例(CRUD)—全XML开发
目录结构
基础配置
- DAO接口
package com.bdit.mapper;
import com.bdit.pojo.Studentsp;
import java.util.List;
/**
* @Package: com.bdit.mapper
* @ClassName: IStudentspMapper
* @Author: Ling
* @Date: 2020/11/14 10:50
* @Description:DAO
*/
public interface IStudentspMapper {
/**
*@Author: Ling
*@Date: 2020-11-14 10:53:12
*@return: 增加
*/
public int save(Studentsp studentsp);
/**
*@Author: Ling
*@Date: 2020-11-14 10:53:35
*@return: 删除
*/
public int delect(Integer integer);
/**
*@Author: Ling
*@Date: 2020-11-14 10:53:44
*@return: 修改
*/
public int update(Studentsp studentsp);
/**
*@Author: Ling
*@Date: 2020-11-14 10:53:54
*@return: 安装ID查询
*/
public Studentsp queryId(Integer integer);
/**
*@Author: Ling
*@Date: 2020-11-14 10:54:08
*@return: 查询全部
*/
public List<Studentsp> queryAll();
}
- 实体类
package com.bdit.pojo;
import lombok.Data;
import java.io.Serializable;
/**
* @Package: com.bdit.pojo
* @ClassName: Studentsp
* @Author: Ling
* @Date: 2020/11/14 10:44
* @Description:
*/
@Data
public class Studentsp implements Serializable {
private int stuId;
private String stuName;
private int stuAge;
private String stuScore;
}
- 业务层接口
package com.bdit.service;
import com.bdit.pojo.Studentsp;
import java.util.List;
/**
* @Package: com.bdit.service
* @ClassName: IStudentspService
* @Author: Ling
* @Date: 2020/11/14 11:54
* @Description:业务层
*/
public interface IStudentspService {
/**
*@Author: Ling
*@Date: 2020-11-14 11:56:25
*@return: 增加
*/
public int save(Studentsp studentsp);
/**
*@Author: Ling
*@Date: 2020-11-14 11:56:41
*@return: 删除
*/
public int delect(Integer integer);
/**
*@Author: Ling
*@Date: 2020-11-14 11:56:57
*@return: 修改
*/
public int update(Studentsp studentsp);
/**
*@Author: Ling
*@Date: 2020-11-14 11:57:28
*@return: 按照ID查询
*/
public Studentsp queryId(Integer integer);
/**
*@Author: Ling
*@Date: 2020-11-14 11:57:45
*@return: 查询全部
*/
public List<Studentsp> queryAll();
}
- 业务层实现类
package com.bdit.service.impl;
import com.bdit.mapper.IStudentspMapper;
import com.bdit.pojo.Studentsp;
import com.bdit.service.IStudentspService;
import java.util.List;
/**
* @Package: com.bdit.service
* @ClassName: StudentspService
* @Author: Ling
* @Date: 2020/11/14 11:58
* @Description:业务层
*/
public class StudentspServiceImpl implements IStudentspService {
private IStudentspMapper studentspMapper;
public void setStudentspMapper(IStudentspMapper studentspMapper) {
this.studentspMapper = studentspMapper;
}
@Override
public int save(Studentsp studentsp) {
return studentspMapper.save(studentsp);
}
@Override
public int delect(Integer integer) {
return studentspMapper.delect(integer);
}
@Override
public int update(Studentsp studentsp) {
return studentspMapper.update(studentsp);
}
@Override
public Studentsp queryId(Integer integer) {
return studentspMapper.queryId(integer);
}
@Override
public List<Studentsp> queryAll() {
return studentspMapper.queryAll();
}
}
- 测试类
package com.bdit.text;
import com.bdit.pojo.Studentsp;
import com.bdit.service.IStudentspService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
/**
* @Package: com.bdit.text
* @ClassName: Springtext
* @Author: Ling
* @Date: 2020/11/14 13:52
* @Description:
*/
public class Springtext {
@Test
public void queryAllSpring(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-mybatis.xml");
IStudentspService iStudentspService = context.getBean("studentspservic", IStudentspService.class);
List<Studentsp> studentspList = iStudentspService.queryAll();
for (Studentsp s : studentspList){
System.out.println("Spring= "+s);
}
}
@Test
public void saveSpring(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-mybatis.xml");
IStudentspService iStudentspService = context.getBean("studentspservic",IStudentspService.class);
Studentsp studentsp = new Studentsp();
studentsp.setStuName("甲四");
studentsp.setStuAge(23);
studentsp.setStuScore("98.23");
int a = iStudentspService.save(studentsp);
if (a>0){
System.out.println("添加成功= "+a);
}else{
System.out.println("添加失败= "+a);
}
}
@Test
public void delectSpring(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-mybatis.xml");
IStudentspService iStudentspService = context.getBean("studentspservic",IStudentspService.class);
int a = iStudentspService.delect(1004);
if (a>0){
System.out.println("删除成功= "+a);
}else{
System.out.println("删除失败= "+a);
}
}
@Test
public void queryIdSpring(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-mybatis.xml");
IStudentspService iStudentspService = context.getBean("studentspservic",IStudentspService.class);
Studentsp studentsp = iStudentspService.queryId(1003);
System.out.println(studentsp);
}
@Test
public void updateSpring() {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-mybatis.xml");
IStudentspService iStudentspService = context.getBean("studentspservic", IStudentspService.class);
Studentsp s = iStudentspService.queryId(1002);
s.setStuName("修改");
int a = iStudentspService.update(s);
if (a > 0) {
System.out.println("修改成功= " + a);
} else {
System.out.println("修改失败= " + a);
}
}
}
- spring-mybatis.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
https://www.springframework.org/schema/context/spring-context.xsd
">
<!--配置业务层-->
<bean id="studentspservic" class="com.bdit.service.impl.StudentspServiceImpl">
<property name="studentspMapper" ref="IStudentspMapper">
<!--
name 是DAO层Set方法的返回值
ref 链接是DAO层接口
class是业务层的实现类(接口实现类,实现是业务层的),但在类中创建DAO层的类方法,并却实现其Set方法
-->
</property>
</bean>
<!--配置DAO层-->
<!--将数据库链接交给spring框架,通过文件加载器来加载bd.properties-->
<context:property-placeholder location="db.properties"></context:property-placeholder>
<!--配置数据源-->
<bean id="dataService" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置mybatis的Sqlsession工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据
将 数据库的链接有关的数据,注入工厂中-->
<property name="dataSource" ref="dataService"></property>
<!--配置别名-->
<property name="typeAliasesPackage" value="com.bdit.pojo"></property>
</bean>
<!--创建DAO代理实现类的扫描器-->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.bdit.mapper"></property>
</bean>
</beans>
- mybatis-confing.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
- db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/stu_vue?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=1234
- IStudentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bdit.mapper.IStudentMapper">
<insert id="save" parameterType="student">
INSERT INTO studentsp(stuId,stuName,stuAge,stuScore) VALUES(#{stuId},#{stuName},#{stuAge},#{stuScore})
</insert>
<delete id="delect" parameterType="int">
DELETE FROM studentsp WHERE stuId=#{stuId}
</delete>
<update id="update" parameterType="student">
UPDATE studentsp SET stuName=#{stuName},stuAge=#{stuAge},stuScore=#{stuScore} WHERE stuId=#{stuId}
</update>
<select id="queryId" parameterType="int" resultType="student">
SELECT <include refid="srudetall"/> FROM studentsp WHERE stuId = #{stuId}
</select>
<select id="queryAll" resultType="student">
SELECT <include refid="srudetall"/> FROM studentsp
</select>
<sql id="srudetall">
stuId,stuName,stuAge,stuScore
</sql>
</mapper>
在pom.xml中还要添加,来强制加载java下的xml
<build>
<!--加载java目录下的xml文件-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<!-- <resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>-->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
6、 IOC综合案例(CRUD)—半注解半XML开发
目录结构
基础配置
- DAO层接口类
package com.bdit.mapper;
import com.bdit.pojo.Student;
import java.util.List;
/**
* @Package: com.bdit.mapper
* @ClassName: IStudentMapper
* @Author: Ling
* @Date: 2020/11/18 10:11
* @Description:
*/
public interface IStudentMapper {
public int save(Student student);
public int update(Student student);
public int delete(Integer integer);
public Student queryById(Integer integer);
public List<Student> queryAll();
}
- 实体类
package com.bdit.pojo;
import lombok.Data;
import java.io.Serializable;
/**
* @Package: com.bdit.pojo
* @ClassName: Student
* @Author: Ling
* @Date: 2020/11/16 20:45
* @Description:实体类
*/
@Data
public class Student implements Serializable {
private int stuId;
private String stuName;
private int stuAge;
private String stuScore;
}
- 业务层接口类
package com.bdit.service;
import com.bdit.pojo.Student;
import java.util.List;
/**
* @Package: com.bdit.service
* @ClassName: IStudentService
* @Author: Ling
* @Date: 2020/11/16 20:47
* @Description:业务层接口
*/
public interface IStudentService {
public int save(Student student);
public int update(Student student);
public int delete(Integer integer);
public Student queryById(Integer integer);
public List<Student> queryAll();
}
- 业务层接口实现类
package com.bdit.service.impl;
import com.bdit.mapper.IStudentMapper;
import com.bdit.pojo.Student;
import com.bdit.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Package: com.bdit.service.impl
* @ClassName: StudentServiceImpl
* @Author: Ling
* @Date: 2020/11/16 20:48
* @Description:业务层实体类
*/
@Service
public class StudentServiceImpl implements IStudentService {
//业务层调用持久层(dao层)
@Autowired
private IStudentMapper iStudentMapper;
public void setStudentMapper(IStudentMapper istudentMapper) {
iStudentMapper = istudentMapper;
}
@Override
public int save(Student student) {
return iStudentMapper.save(student);
}
@Override
public int update(Student student) {
return iStudentMapper.update(student);
}
@Override
public int delete(Integer integer) {
return iStudentMapper.delete(integer);
}
@Override
public Student queryById(Integer integer) {
return iStudentMapper.queryById(integer);
}
@Override
public List<Student> queryAll() {
return iStudentMapper.queryAll();
}
}
- spring-config.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
https://www.springframework.org/schema/context/spring-context.xsd
">
<!--
1、配置业务层
2、配置DAO层
1)、解析链接数据库的文件的参数
2)、链接数据库
3、配置数据库的工厂
4、扫描DAO的代理实现类
-->
<context:property-placeholder location="db.properties"></context:property-placeholder>
<bean id="datadeploy" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datadeploy"></property>
<property name="typeAliasesPackage" value="com.bdit.pojo"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.bdit.mapper"></property>
</bean>
<!--告诉spring启动扫描-->
<context:component-scan base-package="com.bdit"/>
</beans>
- 测试类
package com.bdit.text;
import com.bdit.pojo.Student;
import com.bdit.service.IStudentService;
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;
/**
* @Package: com.bdit.text
* @ClassName: TextZj
* @Author: Ling
* @Date: 2020/11/16 11:34
* @Description:
*/
//明确Runner对象,使用Spring框架中的Runner代替Junit中的Runnit对象
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-config.xml")
public class Text {
@Autowired
private IStudentService iStudentService;
@Test
public void textbzj(){
List<Student> list = iStudentService.queryAll();
for (Student s : list){
System.out.println(s);
}
}
}
7、全注解(复杂版)
目录结构
基本结构
- dao层
package com.bdit.mapper;
import com.bdit.pojo.Student;
import java.util.List;
/**
* @Package: com.bdit.mapper
* @ClassName: IStudentMapper
* @Author: Ling
* @Date: 2020/11/18 10:11
* @Description:
*/
public interface IStudentMapper {
public int save(Student student);
public int update(Student student);
public int delete(Integer integer);
public Student queryById(Integer integer);
public List<Student> queryAll();
}
- 实体类
package com.bdit.pojo;
import lombok.Data;
import java.io.Serializable;
/**
* @Package: com.bdit.pojo
* @ClassName: Student
* @Author: Ling
* @Date: 2020/11/16 20:45
* @Description:实体类
*/
@Data
public class Student implements Serializable {
private int stuId;
private String stuName;
private int stuAge;
private String stuScore;
}
- 业务层接口
package com.bdit.service;
import com.bdit.pojo.Student;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @Package: com.bdit.service
* @ClassName: IStudentService
* @Author: Ling
* @Date: 2020/11/16 20:47
* @Description:业务层接口
*/
public interface IStudentService {
public int save(Student student);
public int update(Student student);
public int delete(Integer integer);
public Student queryById(Integer integer);
public List<Student> queryAll();
}
- 业务层实现类
package com.bdit.service.impl;
import com.bdit.mapper.IStudentMapper;
import com.bdit.pojo.Student;
import com.bdit.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Package: com.bdit.service.impl
* @ClassName: StudentServiceImpl
* @Author: Ling
* @Date: 2020/11/16 20:48
* @Description:业务层实体类
*/
// 全注解 复杂版
@Service
public class StudentServiceImpl implements IStudentService {
//业务层调用持久层(dao层)
@Autowired
private IStudentMapper iStudentMapper;
public void setStudentMapper(IStudentMapper istudentMapper) {
iStudentMapper = istudentMapper;
}
@Override
public int save(Student student) {
return iStudentMapper.save(student);
}
@Override
public int update(Student student) {
return iStudentMapper.update(student);
}
@Override
public int delete(Integer integer) {
return iStudentMapper.delete(integer);
}
@Override
public Student queryById(Integer integer) {
return iStudentMapper.queryById(integer);
}
@Override
public List<Student> queryAll() {
return iStudentMapper.queryAll();
}
}
- spring配置
package com.bdit.confing;
import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* @Package: com.bdit.confing
* @ClassName: SpringConfig
* @Author: Ling
* @Date: 2020/11/18 10:57
* @Description:全注解 复杂版
*/
// 全注解 复杂版
//Spring配置类,框架启动入口
@Configuration
@ComponentScan({"com.bdit"})
public class SpringConfig {
@Bean(value = {"duridDataSource"})
public DataSource dataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
druidDataSource.setUrl("jdbc:mysql://localhost:3306/stu_vue?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8");
druidDataSource.setUsername("root");
druidDataSource.setPassword("1234");
return druidDataSource;
}
@Bean(value = {"sqlSessionFactory"})
public SqlSessionFactoryBean createSqlSessionFactoryBean(@Qualifier("duridDataSource") DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//设置数据源
sqlSessionFactoryBean.setDataSource(dataSource);
//设置别名 批量
sqlSessionFactoryBean.setTypeAliasesPackage("com.bdit.pojo");
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer createMapperScannerConfigurer() {
MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
scannerConfigurer.setBasePackage("com.bdit.mapper");
return scannerConfigurer;
}
}
- 测试类
package com.bdit.text;
import com.bdit.confing.SpringConfig;
import com.bdit.pojo.Student;
import com.bdit.service.IStudentService;
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;
/**
* @Package: com.bdit.text
* @ClassName: TextZj
* @Author: Ling
* @Date: 2020/11/16 11:34
* @Description:
*/
//明确Runner对象,使用Spring框架中的Runner代替Junit中的Runnit对象
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration( classes = {SpringConfig.class})
public class Text {
@Autowired
private IStudentService iStudentService;
// 全注解 复杂版
@Test
public void textzj(){
List<Student> list = iStudentService.queryAll();
for (Student s : list){
System.out.println(" -"+s);
}
}
}
8、全注解
目录结构
基本结构
与7几乎没变化
DataSourceConfig.class
package com.bdit.confing;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
/**
* @Package: com.bdit.confing
* @ClassName: DataSourceConfig
* @Author: Ling
* @Date: 2020/11/18 11:12
* @Description:
*/
@PropertySource(value = {"classpath:db.properties"})
public class DataSourceConfig {
@Value("${jdbc.driver}")
private String driverClassName;
@Value("${jdbc.url}")
private String url;
@Value( "${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean(value = "druidDataSource")
public DataSource createDataSource(){
DruidDataSource druidDataSource=new DruidDataSource();
druidDataSource.setDriverClassName(driverClassName);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
return druidDataSource;
}
}
MyBatisConfig.class
package com.bdit.confing;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* @Package: com.bdit.confing
* @ClassName: MyBatisConfig
* @Author: Ling
* @Date: 2020/11/18 11:14
* @Description:
*/
@Configuration
public class MyBatisConfig {
@Bean(value = {"sqlSessionFactory"})
public SqlSessionFactoryBean createSqlSessionFactoryBean(@Qualifier("druidDataSource") DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//设置数据源
sqlSessionFactoryBean.setDataSource(dataSource);
//设置别名 批量
sqlSessionFactoryBean.setTypeAliasesPackage("com.bdit.pojo");
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer createMapperScannerConfigurer() {
MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
scannerConfigurer.setBasePackage("com.bdit.mapper");
return scannerConfigurer;
}
}
SpringConfig.class
package com.bdit.confing;
import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import javax.sql.DataSource;
/**
* @Package: com.bdit.confing
* @ClassName: SpringConfig
* @Author: Ling
* @Date: 2020/11/18 10:57
* @Description:全注解 复杂版
*/
// 全注解 简化版
//Spring配置类,框架启动入口
@Configuration
@ComponentScan({"com.bdit"})
@Import({DataSourceConfig.class,MyBatisConfig.class})
public class SpringConfig {
}
其余几乎不变
【在 resours 下创建的是文件不是包,所以要一层一层的创建,不能直接xxx.xxx.xxx来创建】
SpringConfig.class
package com.bdit.confing;
import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import javax.sql.DataSource;
/**
* @Package: com.bdit.confing
* @ClassName: SpringConfig
* @Author: Ling
* @Date: 2020/11/18 10:57
* @Description:全注解 复杂版
*/
// 全注解 简化版
//Spring配置类,框架启动入口
@Configuration
@ComponentScan({"com.bdit"})
@Import({DataSourceConfig.class,MyBatisConfig.class})
public class SpringConfig {
}
其余几乎不变
【在 resours 下创建的是文件不是包,所以要一层一层的创建,不能直接xxx.xxx.xxx来创建】