一、Spring概述
Spring是一个轻量级的控制反转(IOC)和面向切面(AOP)的容器(框架)。
二、Spring基础程序
1、pom.xml中导入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
2、编写一个实体类
package com.demo.pojo;
public class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("Hello,"+ name );
}
}
3、编写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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--bean就是java对象 , 由Spring创建和管理-->
<bean id="hello" class="com.demo.pojo.Hello">
<property name="name" value="Spring"/>
</bean>
</beans>
4、测试Spring程序
import com.demo.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
//解析beans.xml文件 , 生成管理相应的Bean对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//getBean : 参数即为spring配置文件中bean的id .
Hello hello = (Hello) context.getBean("hello");
hello.show();
}
}
三、IOC创建对象方式
1、利用构造器注入
<!-- 第一种根据index参数下标设置 -->
<bean id="hello" class="com.demo.pojo.Hello">
<!-- index指构造方法 , 下标从0开始 -->
<constructor-arg index="0" value="liusize1"/>
</bean>
<!-- 第二种根据参数名字设置 -->
<bean id="hello" class="com.demo.pojo.Hello">
<!-- name指参数名 -->
<constructor-arg name="name" value="liusize2"/>
</bean>
<!-- 第三种根据参数类型设置 -->
<bean id="hello" class="com.demo.pojo.Hello">
<constructor-arg type="java.lang.String" value="liusize3"/>
</bean>
2、利用Set注入(常用)
创建一个Address类
package com.demo.pojo;
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
创建一个Student类
package com.demo.pojo;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;
public void setName(String name) {
this.name = name;
}
public void setAddress(Address address) {
this.address = address;
}
public void setBooks(String[] books) {
this.books = books;
}
public void setHobbys(List<String> hobbys) {
this.hobbys = hobbys;
}
public void setCard(Map<String, String> card) {
this.card = card;
}
public void setGames(Set<String> games) {
this.games = games;
}
public void setWife(String wife) {
this.wife = wife;
}
public void setInfo(Properties info) {
this.info = info;
}
public void show(){
System.out.println("name="+ name
+ ",address="+ address.getAddress()
+ ",books="
);
for (String book:books){
System.out.print("<<"+book+">>\t");
}
System.out.println("\n爱好:"+hobbys);
System.out.println("card:"+card);
System.out.println("games:"+games);
System.out.println("wife:"+wife);
System.out.println("info:"+info);
}
}
注册Bean
<bean id="addr" class="com.demo.pojo.Address">
<property name="address" value="南昌"/>
</bean>
<bean id="student" class="com.demo.pojo.Student">
<!-- 注入常量-->
<property name="name" value="凯影"/>
<!-- 注入类,ref是引用bean中注册的另一个类-->
<property name="address" ref="addr"/>
<!-- 注入数组-->
<property name="books">
<array>
<value>机器学习</value>
<value>深度学习</value>
<value>人工智能</value>
</array>
</property>
<!-- 注入List -->
<property name="hobbys">
<list>
<value>英雄联盟</value>
<value>跑步</value>
<value>看电影</value>
</list>
</property>
<!-- 注入Map -->
<property name="card">
<map>
<entry key="中国农业银行" value="456456456465456"/>
<entry key="中国建设银行" value="1456682255511"/>
</map>
</property>
<!-- 注入set-->
<property name="games">
<set>
<value>LOL</value>
<value>BOB</value>
<value>COC</value>
</set>
</property>
<!-- 注入Null-->
<property name="wife"><null/></property>
<!-- 注入Properties注入-->
<property name="info">
<props>
<prop key="学号">20181944</prop>
<prop key="性别">男</prop>
<prop key="姓名">艾克</prop>
</props>
</property>
</bean>
结果展示
四、自动装配
Spring的自动装配需要从两个角度来实现,或者说是两个操作:
- 组件扫描(component scanning):spring会自动发现应用上下文中所创建的bean;
- 自动装配(autowiring):spring自动满足bean之间的依赖,也就是我们说的IOC/DI;
1、在spring配置文件中引入context文件头
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
2、开启属性注解支持
<context:annotation-config/>
3、Dog类
public class Dog {
public void shout() {
System.out.println("wang~");
}
}
4、User类
public class User {
@Autowired
private Dog dog;
private String str;
public User() {
}
public User(Dog dog, String str) {
this.dog = dog;
this.str = str;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
5、注册bean
<bean id="dog" class="com.demo.pojo.Dog"/>
<bean id="user" class="com.demo.pojo.User">
<property name="str" value="liusize"/>
</bean>
@Autowired
@Autowired是按类型自动转配的,不支持id匹配。
@Qualifier
@Autowired加上@Qualifier则可以根据id自动装配
@Autowired
@Qualifier(value = "dog1")
@Resource
@Resource先按id方式查找装配,如查不到再按类型自动装配
小结
@Autowired与@Resource异同:
1、@Autowired与@Resource都可以用来装配bean。都可以写在字段上,或写在setter方法上。
2、@Autowired默认按类型装配(属于spring规范),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用
3、@Resource(属于J2EE复返),默认按照名称进行装配,名称可以通过name属性进行指定。如果没有指定name属性,当注解写在字段上时,默认取字段名进行按照名称查找,如果注解写在setter方法上默认取属性名进行装配。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。
它们的作用相同都是用注解方式注入对象,但执行顺序不同。@Autowired先byType,@Resource先byName。
五、使用注解开发
1、在配置文件中引入一个context约束
<?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">
</beans>
2、配置扫描哪些包下的注解
<!--指定注解扫描包-->
<context:component-scan base-package="com.demo.pojo"/>
3、在指定包下编写类,增加注解
@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
@Value("螳螂")
public String name;
}
@Component三个衍生注解
为了更好的进行分层,Spring可以使用其它三个注解,功能一样
- @Controller:web层
- @Service:service层
- @Repository:dao层
六、Spring-Mybatis
1、导入依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
</dependencies>
2、编写实体类
public class User {
private int id;
private String name;
private String pwd;
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
3、配置mybatis-config.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>
<!--起别名-->
<typeAliases>
<typeAlias type="com.demo.pojo.User" alias="user"/>
</typeAliases>
</configuration>
4、编写UserMapper
public interface UserMapper {
public List<User> selectUser();
}
5、编写UserMapper.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.demo.dao.UserMapper">
<select id="selectUser" resultType="user">
select * from lsz_user
</select>
</mapper>
6、编写UserMapperImpl
public class UserMapperImpl implements UserMapper {
//sqlSession不用我们自己创建了,Spring来管理
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
7、编写Spring配置
<?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">
<!--配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--配置SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--关联Mybatis-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/demo/dao/*.xml"/>
</bean>
<!--注册sqlSessionTemplate , 关联sqlSessionFactory-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--利用构造器注入-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!--注册实现类-->
<bean id="userMapper" class="com.demo.dao.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
</beans>
8、测试
public class Test {
public static void main(String[] args) {
//解析beans.xml文件 , 生成管理相应的Bean对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserMapper mapper = (UserMapper) context.getBean("userMapper");
List<User> user = mapper.selectUser();
System.out.println(user);
}
}
七、AOP的动态代理
八、声明式事务
参考视频:【狂神说Java】Spring5最新完整教程IDEA版通俗易懂