1、Hello Spring
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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
<bean id = 别名 class = 类名>
<property name = 属性名 values = 具体值(基本数据类型)>
<property name = 属性名 ref = 引用Spring中创建好的对象(其他bean的id)>
</beans>
-->
<bean id="hello" class="com.hz.hello">
<property name="str" value="Spring"/>
</bean>
</beans>
hello.java
public class hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "hello{" +
"str='" + str + '\'' +
'}';
}
}
test.java
public class test {
public static void main(String[] args) {
//获取Spring类型的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
hello h = (hello) context.getBean("hello");
System.out.println(h.toString());
}
}
1.1 IOC创建对象
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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello1" class="com.hz.hello">
<!--
俩种赋值方式:
1、下标赋值(index)
2、通过类型赋值(type)
3、通过参数名赋值
-->
<constructor-arg index="0" value="this_name"/>
<constructor-arg type="java.lang.String" value="this_name"/>
<constructor-arg name="name" value="名字"/>
</bean>
</beans>
2、Spring配置
别名
<alias name="hello" alias="h1"/>
<bean id = "hello" class="com.hz.hello" name="user1,user2"/?
Bean配置
<!--
id : bean的唯一标识符
class : bean对象的类名(包名+类名)
name : 别名,一个id可以有多个别名
-->
import
一般用于团队开发,可以将多个配置文件导入合并为一个
<import resource="beans.xml"/>
3、依赖注入
3.1 构造器注入
3.2 Set注入
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id = "address" class="com.hz.Address">
<property name="address" value="地址"/>
</bean>
<bean id = "student" class="com.hz.Student">
<property name="name">
<null/>
</property>
<property name="address" ref="address"/>
<property name="books" >
<array>
<value>book1</value>
<value>book2</value>
<value>book3</value>
</array>
</property>
<property name="list">
<list>
<value>list1</value>
<value>list1</value>
<value>list3</value>
</list>
</property>
<property name="map">
<map>
<entry key="map1" value="value1"/>
<entry key="map2" value="value1"/>
<entry key="map3" value="value1"/>
</map>
</property>
<property name="set">
<set>
<value>set1</value>
<value>set2</value>
<value>set2</value>
</set>
</property>
<property name="properties">
<props>
<prop key="driver">驱动</prop>
</props>
</property>
</bean>
</beans>
3.3 拓展方式注入
c/p命名格式
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<C命名格式:xmlns:c="http://www.springframework.org/schema/c"/>
<p命名格式:xmlns:p="http://www.springframework.org/schema/p">
<bean id="beanTwo" class="x.y.ThingTwo"/>
<bean id="beanThree" class="x.y.ThingThree"/>
<!-- traditional declaration with optional argument names -->
<bean id="beanOne" class="x.y.ThingOne">
<constructor-arg name="thingTwo" ref="beanTwo"/>
<constructor-arg name="thingThree" ref="beanThree"/>
<constructor-arg name="email" value="something@somewhere.com"/>
</bean>
<!-- c-namespace declaration with argument names -->
<bean id="beanOne" class="x.y.ThingOne" c:thingTwo-ref="beanTwo"
c:thingThree-ref="beanThree" c:email="something@somewhere.com"/>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/mydb"
p:username="root"
p:password="misterkaoli"/>
</beans>
4、Bean自动装载
4.1 Bean作用域
Scope | Description |
---|---|
singleton | (Default) Scopes a single bean definition to a single object instance for each Spring IoC container. |
prototype | Scopes a single bean definition to any number of object instances. |
request | Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext . |
session | Scopes a single bean definition to the lifecycle of an HTTP Session . Only valid in the context of a web-aware Spring ApplicationContext . |
application | Scopes a single bean definition to the lifecycle of a ServletContext . Only valid in the context of a web-aware Spring ApplicationContext . |
websocket | Scopes a single bean definition to the lifecycle of a WebSocket . Only valid in the context of a web-aware Spring ApplicationContext . |
singleton - 单例模式(每次使用后创建对象一致)
prototype - 多例模式(每次使用创建一个新的对象)
<bean id="loginAction" class="com.something.LoginAction" scope="request"/>
4.2 自动装配
4.2.1 xml自动装配
<bean id="myCommand" class="fiona.apple.AsyncCommand" scope="prototype">
<!-- inject dependencies here as required -->
</bean>
<!-- commandProcessor uses statefulCommandHelper -->
<bean id="commandManager" class="fiona.apple.CommandManager" autowird = "byname">
<!-- 自动在容器中查找对应属性名对应的bean-->
</bean>
4.2.2 使用注解
-
导入约束
-
配置注解支持
<?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"> <!--开启注解支持--> <context:annotation-config/> <!-- xmlns:context="http://www.springframework.org/schema/context" ...https://www.springframework.org/schema/context/spring-context.xsd" --> </beans>
@Autowired
使用该注释可以不用set方法
public class People{
@Autowired(required = false) //允许为空
@Qualifier(value="bean") //设置属性名,byName使用"bean"的bean
String name;
}
@Resource 先匹配类型再匹配属性名
@Resource(name = “name”)
区别:
- 都用于自动装配
- @Autowired默认通过bytype方式实现,存在多个同类型时再通过byname查找
- @Resouce默认通过byName,找不到通过bytype
5、注解开发
注解约束
<?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">
<!--扫描下面的包,这个包下注解生效-->
<context:component-scan base-package="com.hz.pojo">
<!--开启注解支持-->
<context:annotation-config/>
<!-- xmlns:context="http://www.springframework.org/schema/context"
...https://www.springframework.org/schema/context/spring-context.xsd"
-->
</beans>
@Component
//等价于<bean id="student" class="com.hz.Student"/>
public class User(){
@Value("名字")
//等价于<property name="name" values="名字">
private String name;
}
衍生注解
- Dao:@Repository
- service:@Service
- controller:@Controller
6、Java方式配置Spring
配置文件
@Configuration
@CompontScan(包名);
@Import(类名.class)//导入
public class Config(){
//方法名相当于xml中的id
@Bean
public User getuser(){
return new User();
}
}
测试类
public class test {
public static void main(String[] args) {
ApplicationContext context1 = new ClassPathXmlApplicationContext(Config.class);
User user = context1.getBean("getuser");
}
}
7、代理模式
SpringIOP底层
代理模式分类:
-
静态代理
-
动态代理
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VDS9DiKh-1626595854365)(https://www.runoob.com/wp-content/uploads/2014/08/20201015-proxy.svg)]
角色:
- 抽象角色(接口)
- 事实角色
- 代理角色
- 客户
步骤:
- 接口
- 真实角色
- 代理角色
- 客户端访问
7.2 动态代理
- 动态代理的代理类是动态生成的
- 动态代理分为俩大类:基于接口的动态代理,基于类的动态代理
- 基于接口–jdk动态代理
- 基于类–cglib
- java字节码实现
两个类:Proxy,invocationHandler
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Poxy implements InvocationHandler {
//被代理的接口
private rent re;
public void setRent(rent re){
this.re = re;
}
public Object getProxy(){
Proxy.newProxyInstance(this.getClass().getClassLoader(),re.getClass().getInterfaces(),this);
}
//处理代理实例并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object invoke = method.invoke(re, args);
return invoke;
}
//参数
//proxy - 调用该方法的代理实例
//method -所述方法对应于调用代理实例上的接口方法的实例。方法对象的声明类将是该方法声明的接口,它可以是代理类继承该方法的代理接口的超级接口。
//args -包含的方法调用传递代理实例的参数值的对象的阵列,或null如果接口方法没有参数。原始类型的参数包含在适当的原始包装器类的实例中,例如java.lang.Integer或java.lang.Boolean 。
}
public class Client {
public static void main(String[] args) {
//真实角色
Host host = new Host();
//代理实例的调用处理程序
Poxy proxy = new Poxy();
proxy.setRent(host); //将真实角色放置进去!
Rent p = (Rent)proxy.getProxy(); //动态生成对应的代理类!
p.rent();
}
}
8、AOP
pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.7</version>
</dependency>
AOP实现的三种方式
1、通过Spring AOP实现
<?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: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="userservice" class="service.UserServiceImpl"/>
<bean id="log" class="log.Log"/>
<bean id="AfterLog" class="log.AfterLog"/>
<!--配置AOP需要导入AOP约束-->
<aop:config>
<!--切入点 expression:表达式 execution(要执行的位置:*(修饰词) *(返回值) *(类名) *(方法名) *(参数))-->
<aop:pointcut id="pointcut" expression="execution(* service.UserServiceImpl.*(..))"/>
<!--执行环绕增加-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="AfterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
2、自定义
<?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: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="userservice" class="service.UserServiceImpl"/>
<bean id="log" class="log.Log"/>
<bean id="AfterLog" class="log.AfterLog"/>
<bean id="diy" class="log.DiyPoint"/>
<!--配置AOP需要导入AOP约束-->
<aop:config>
<!--切入点 expression:表达式 execution(要执行的位置:*(修饰词) *(返回值) *(类名) *(方法名) *(参数))-->
<!-- <aop:pointcut id="pointcut" expression="execution(* service.UserServiceImpl.*(..))"/>-->
<!-- <!–执行环绕增加–>-->
<!-- <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>-->
<!-- <aop:advisor advice-ref="AfterLog" pointcut-ref="pointcut"/>-->
<!--自定义切面-->
<aop:aspect ref="diy">
<aop:pointcut id="pointcut" expression="execution(* service.UserServiceImpl.*(..))"/>
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:after method="after" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
</beans>
3、注解实现
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {
@Before("execution(* service.UserServiceImpl.*(..))")
public void before(){
System.out.println("=========方法执行前==========");
}
//在环绕增强中,我们可以给定一个参数,代表我们获取处理切入的点
@Around("execution(* service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
//执行方法
Object proceed = jp.proceed();
System.out.println("环绕后");
}
}
9、 整合
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">
<parent>
<artifactId>sprinf-study</artifactId>
<groupId>com.hz</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-mybatis</artifactId>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.6</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</dependencies>
</project>
src/resources
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="qzzx91112"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="mapper.UserMapper"/>
</mappers>
</configuration>
测试类
public class test {
@Test
public void test() throws IOException {
String resources = "mybastic.xml";
InputStream resourceAsStream = Resources.getResourceAsStream(resources);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = factory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> list = mapper.selectUser();
for (User user : list) {
System.out.println(user);
}
}
}
9.2
<?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: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.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="qzzx91112"/>
</bean>
<!-- sqlsessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 绑定mybatis-->
<property name="configLocation" value="classpath:mybastic.xml"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 只能构造器注入,无set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<bean id="userMapper" class="mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSession"/>
</bean>
</beans>
@Test
public void MyTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}
public class UserMapperImpl implements UserMapper {
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
public List<User> selectUser() {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.selectUser();
// return sqlSessionTemplate.selectList("SELECT * FROM user");
}
}
10、事务
<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"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<import resource="spring-dao.xml"/>
<bean id="userMapper" class="mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSession"/>
</bean>
<bean id="UserMapper2" class="mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
<property name="sqlSessionTemplate" ref="sqlSession"/>
</bean>
<aop:config>
<aop:pointcut id="txPoint" expression="execution(* mapper.*(..))"/>
</aop:config>
<!--配置声明式事务-->
<bean id="transcationManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 结合AOP实现事务的织入
配置事务通知
-->
<tx:advice id="txAdvice" transaction-manager="transcationManger">
<!-- 给方法配置事务
REQUIRED:支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。
SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行。
MANDATORY:支持当前事务,如果当前没有事务,就抛出异常。
REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。
NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。
NESTED:支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务。-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
</beans>