创建接口和实现类
接口UserDao
package com.kuang.dao;
/*创建一个接口*/
public interface UserDao {
void getUser();
}
实现类UserDaoImpl
package com.kuang.dao;
/*接口实现类*/
public class UserDaoImpl implements UserDao {
public void getUser() {
System.out.println("默认获取用户的数据");
}
}
service接口:
package com.kuang.service;
public interface UserService {
void getUser();
}
实现类:
package com.kuang.service;
import com.kuang.dao.UserDao;
import com.kuang.dao.UserDaoImpl;
public class UserServiceImpl implements UserService {
/*想要调用dao层除了继承,还有一种组合的方式*/
private UserDao userDao = new UserDaoImpl();
public void getUser() {
userDao.getUser();
}
}
如何在service层调用dao层接口
测试类:
用户不用去管dao接口层怎么实现,只需要去调用业务层代码即可。
import com.kuang.service.UserServiceImpl;
public class MyTest {
public static void main(String[] args) {
/*用户实际调用的是业务层(service),dao层他们不需要接触*/
UserServiceImpl userService = new UserServiceImpl();
userService.getUser();
}
}
/*想要调用dao层除了继承,还有一种组合的方式*/
private UserDao userDao;
/*动态注入对象*/
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
import com.kuang.dao.UserDaoMysqlImpl;
import com.kuang.service.UserServiceImpl;
public class MyTest {
public static void main(String[] args) {
/*用户实际调用的是业务层(service),dao层他们不需要接触*/
UserServiceImpl userService = new UserServiceImpl();
userService.setUserDao(new UserDaoMysqlImpl());
userService.getUser();
}
}
思想本质
:程序员不用再去管对象的创建,对象的创建交给用户自己diy。系统的耦合性大大降低
获取依赖对象的方式反转了,原本对象是有业务层来创建的,现在是由用户自己来创建,降低了对象之间的耦合性。
创建一个ApplicationContext.xml文件,通过xml配置来实现对象的创建。标签中的bean标签就是相当于以前new的对象
标签与传统创建对象对比
ApplicationContext.xml
<bean id="hello" class="com.kuang.pojo.Hello">
<property name="str" value="spring"></property>
</bean>
<bean id="userdaoimpl" class="com.kuang.dao.UserDaoImpl"></bean>
<bean id="mysqlimpl" class="com.kuang.dao.UserDaoMysqlImpl"></bean>
<bean id="userserviceimpl" class="com.kuang.service.UserServiceImpl">
<property name="userDao" ref="mysqlimpl"></property>
</bean>
Test
public class MyTest {
public static void main(String[] args) {
//获取spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:beans.xml");
//因为我们的对象都在spring中管理了,我们要做的就是去spring容器中取出即可
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
<bean id="hello" class="com.kuang.pojo.Hello">
<property name="str" value="spring">property>
bean>
<bean id="user" class="com.kuang.pojo.User">
<constructor-arg index="0" value="渣渣鑫">constructor-arg>
bean>
<bean id="user" class="com.kuang.pojo.User">
<constructor-arg name="name" value="渣渣鑫">constructor-arg>
bean>
控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用spring后,对象是由spring来创建的。
反转:程序本身不创建对象,而是被动的接收对象
依赖注入:本身就是利用set方法进行注入的
可以将包名简化
之前讲解了
导入Spring依赖:
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>4.1.7.RELEASEversion>
dependency>
创建实体类:
package com.kuang.pojo;
public class Address {
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
package com.kuang.pojo;
import java.net.ServerSocket;
import java.util.*;
public class Student {
private String name;
private Address address;//这里进行了set注入
private String[] books;
private List<String> hobbys;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String[] getBooks() {
return books;
}
public void setBooks(String[] books) {
this.books = books;
}
public List<String> getHobbys() {
return hobbys;
}
public void setHobbys(List<String> hobbys) {
this.hobbys = hobbys;
}
public Map<String, String> getCard() {
return card;
}
public void setCard(Map<String, String> card) {
this.card = card;
}
public Set<String> getGames() {
return games;
}
public void setGames(Set<String> games) {
this.games = games;
}
public String getWife() {
return wife;
}
public void setWife(String wife) {
this.wife = wife;
}
public Properties getInfo() {
return info;
}
public void setInfo(Properties info) {
this.info = info;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address=" + address +
", books=" + Arrays.toString(books) +
", hobbys=" + hobbys +
", card=" + card +
", games=" + games +
", wife='" + wife + '\'' +
", info=" + info +
'}';
}
}
<bean id="address" class="com.kuang.pojo.Address">
<property name="address" value="山西阳泉"/>
bean>
<bean id="student" class="com.kuang.pojo.Student">
<property name="name" value="渣渣鑫">property>
<property name="address" ref="address">property>
<property name="books">
<array>
<value>红楼梦value>
<value>西游记value>
<value>水浒传value>
<value>三国演义value>
array>
property>
<property name="hobbys">
<list>
<value>听歌value>
<value>敲代码value>
<value>看电影value>
list>
property>
<property name="card">
<map>
<entry key="身份证" value="1234567890">entry>
<entry key="银行卡" value="111231434e">entry>
map>
property>
<property name="games">
<set>
<value>LOLvalue>
<value>COCvalue>
<value>BOBvalue>
set>
property>
<property name="wife">
<null/>
property>
<property name="info">
<props>
<prop key="学号">2020100416prop>
<prop key="性别">男prop>
props>
property>
bean>
public class MyTest {
public static void main(String[] args) {
//获取spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//因为我们的对象都在spring中管理了,我们要做的就是去spring容器中取出即可
Student student = (Student) context.getBean("student");
System.out.println(student.toString());
}
}
Student{name='渣渣鑫',
* address=Address{address='山西阳泉'},
* books=[红楼梦, 西游记, 水浒传, 三国演义],
* hobbys=[听歌, 敲代码, 看电影],
* card={身份证=1234567890, 银行卡=111231434e},
* games=[LOL, COC, BOB],
* wife='null', i
* nfo={学号=2020100416, 性别=男}}
导入lombok依赖:可以不用生成get和set代码,使用注解来解决
@Data
@NoArgsConstructor//无参构造
@AllArgsConstructor//所有构造
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.12version>
<scope>providedscope>
dependency>
注解@Component(“别名”)等价于bean标签中的
bean id=“mailService” class=“com.zzx.service.MailService”/
依赖输入可以使用@Autowired注解,等价于
property name=“mailService” ref=“mailService”>
@Service的底层实现还是@Component,这里用service是因为他说服务层,编写代码逻辑的包
p命名和C命名,需要导入xml约束
隐式的自动装配
(重点)会自动在容器上下文查找与自己对象set后面的值相对应的beanid。
吧id修改成dog111就不能自动匹配了,会报空指针异常
使用bytype就会解决上面存在的问题,bytype会自动在容器上下文查找和自己属性值类型相同的bean
使用注解需要插入下面这条约束
xmlns:context="http://www.springframework.org/schema/context"
注解支持的引入
<context:annotation-config/>
如果有多个对象时。只使用@Autowired无法精准匹配到对象,就会报错,这时候加入Qualifier(value = “”)就可以继续使用了。
public class People {
@Autowired
private Cat cat;
@Autowired
@Qualifier(value ="dog1")
private Dog dog;
private String name;
导入context约束
<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">
@Component的衍生注解,本质还是一样的,只是在不同的层用了不同的注解
service层:@Service
上面的注解都是一样的,都是讲某个类注册到spring容器中,装配bean
代理模式就是中介的作用,让用户与厂家不直接接触,而是通过中介来联系。
代码开发步骤:
package com.kuang.demo01;
/*租房的接口--抽象角色*/
public interface Rent {
/*出租房屋的方法*/
public void rent();
}
/*房东是真实角色---租房子*/
public class Host implements Rent{
public void rent() {
System.out.println("房东要出租房子");
}
}
/*代理---中介
* */
public class Proxy implements Rent{
/*这些是代理和房东的事情*/
private Host host;
public Proxy(Host host) {
this.host = host;
}
/*这是代理和租房的事情*/
public void rent() {
host.rent();
}
}
/*客户去租房子
* */
public class Client {
public static void main(String[] args) {
/* *//*传统租房子--客户直接俄找房东*//*
Host host = new Host();
host.rent();*/
/*先有一个房东*/
Host host = new Host();
//代理房东
Proxy proxy = new Proxy(host);
proxy.rent();
}
}
优点:
缺点:
spring.io
AOP (Aspect Orient Programming),直译过来就是 面向切面编程。AOP 是一种编程思想,是面向对象编程(OOP)的一种补充。面向对象编程将程序抽象成各个层次的对象,而面向切面编程是将程序抽象成各个切面。
简单理解就是:把Aop当作是程序的一个插件,当程序想使用的时候就去启动它,不用操作源代码。同时该切面实现了跨越多个应用对象的逻辑。实现模块化。
创建applicationContext.xml配置文件并引入约束
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
beans>
引入依赖
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.4version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>5.2.16.RELEASEversion>
dependency>
讲横切关注点模块化成一个切面
package com.kuang.diy;
/*写一个切面*/
public class DiyPointCut {
public void before(){
System.out.println("=======方法执行前======");
}
public void after(){
System.out.println("=======方法执行后======");
}
}
编写自定义类标签
<bean id="diy" class="com.kuang.diy.DiyPointCut">bean>
<aop:config>
<aop:aspect ref="diy">
<aop:pointcut id="point" expression="execution(* com.kuang.service.UserServiceImpl.*(..))">aop:pointcut>
<aop:before method="before" pointcut-ref="point">aop:before>
<aop:after method="after" pointcut-ref="point">aop:after>
aop:aspect>
aop:config>
测试类
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userservice = (UserService) context.getBean("userService");
userservice.delete();
}
}
导入schema依赖。初始化IOC容器(comtext标签),使用来启动Spring Aop注解模式。
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver">property>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8">property>
<property name="username" value="root">property>
<property name="password" value="010619">property>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="configLocation" value="classpath:mybatis-config.xml">property>
<property name="mapperLocations" value="classpath:com/kuang/mapper/UserMapper.xml">property>
bean>
<bean id="sqlSesion" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory">constructor-arg>
bean>
public class UserMapperImpl implements UserMapper {
//我们的所有操作,都使用sqlSession来执行,现在使用SqlSessionTemplate
private SqlSessionTemplate sqlsession;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlsession = sqlSessionTemplate;
}
public List<User> selectUser() {
UserMapper mapper = sqlsession.getMapper(UserMapper.class);
return mapper.selectUser();
}
public void setSqlsession(SqlSessionTemplate sqlsession) {
this.sqlsession = sqlsession;
}
public SqlSessionTemplate getSqlsession() {
return sqlsession;
}
}
<bean id="userMapper" class="com.kuang.mapper.UserMapperImpl">
<property name="sqlsession" ref="sqlSesion">property>
bean>
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user :userMapper.selectUser())
{
System.out.println(user);
}
依赖的注入
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.0.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.0.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.4version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.2version>
dependency>
dependencies>
事务:
特性就是要么都成功,要么都失败
事务在项目开发中很重要,确保项目的完整性和一致性。
事务的ACID原则:
1、导入依赖:
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.1version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.0.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.0.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.4version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.2version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.12version>
<scope>providedscope>
dependency>
dependencies>
2、创建包:
pojo包:就是普通代码包,主要写一些实体类
与数据库的字段名匹配
@Data
public class User {
private int id;
private String name;
private String pwd;
}
3、写完实体类就要去写接口(UserMapper)
接口里面写增删改查的方法
public interface UserMapper {
public List<User> selectUser();
}
4、导入mybatis配置
mybatis-config.xml
因为使用spring配置,所以mybatis-config.xml的配置都写到spring中去了。
这里主要写别名的标签即可
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.kuang.pojo" >package>
typeAliases>
configuration>
5、整合spring(常见spring-dao.xml)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver">property>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8">property>
<property name="username" value="root">property>
<property name="password" value="010619">property>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="configLocation" value="classpath:mybatis-config.xml">property>
<property name="mapperLocations" value="classpath:com/kuang/mapper/UserMapper.xml">property>
bean>
<bean id="sqlSesion" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory">constructor-arg>
bean>
beans>
6、创建usermapper.xml(编写sql语句的标签)
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.mapper.UserMapper">
<select id="selectUser" resultType="user">
/*查询全部用户*/
SELECT * FROM mybatis.user;
select>
mapper>
7、编写实现类来操作
public class UserMapperImpl implements UserMapper {
//我们的所有操作,都使用sqlSession来执行,现在使用SqlSessionTemplate
private SqlSessionTemplate sqlsession;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlsession = sqlSessionTemplate;
}
public List<User> selectUser() {
UserMapper mapper = sqlsession.getMapper(UserMapper.class);
return mapper.selectUser();
}
public void setSqlsession(SqlSessionTemplate sqlsession) {
this.sqlsession = sqlsession;
}
public SqlSessionTemplate getSqlsession() {
return sqlsession;
}
}