1.Spring
1.1简介
Spring:春天----------------->给软件行业带来了春天
SSH:Struct+Spring+Hibernate
SSM:SpringMVC+Spring+Mybatis
官网:https://spring.io/projects/spring-framework#overview
maven
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.4</version>
</dependency>
1.2优点
- Spring是一个开源的免费的框架
- Spring是一个轻量级,非侵入式框架
- 控制反转(IOC) 面向切面编程(AOP)
- 支持事务的处理,对框架综合支持
- Spring是一个轻量级控制反转(IOC)和面向切面编程的框架
1.3组成
1.4扩展
在spring官网有这个介绍 现代化的java开发
Spring Boot
- 一个快速开发的脚手架
- 基于Spring Boot可以快速开发单个微服务
- 约定大于配置
Spring Cloud
Spring Cloud是基于SpringBoot实现的
2.IOC理论推导
1.UserDao接口
2.UserDaoImpl实现类
3.UserService业务接口
4.UserServicelmpl业务实现类
在之前的业务中,用户需求可能影响原来的代码。修改源代码代价高
所以使用一个set接口,已经发生了革命性变化
private UserDao userDao;
//利用set进行动态实现值的注入
public void setUserDao(UserDao userDao){
this.userDao=userDao;
}
- 之前程序主动创建对象 控制权在程序员手上
- 使用了set注入以后,程序员不再有主动性,被动接受对象
这种思想从本质上解决了问题,程序员不用管理对象的创建,系统的耦合性降低,可以更加专注于业务的实现上
3.HelloSpring
3.1导入Spring相关jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.4</version>
</dependency>
3.2编写相关代码
(1)编写Hello实体类
public class Hello {
private String Str;
@Override
public String toString() {
return "Hello{" +
"Str='" + Str + '\'' +
'}';
}
public String getStr() {
return Str;
}
public void setStr(String str) {
Str = str;
}
}
(2)编写Spring配置文件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"
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.kuang.pojo.Hello">
<!--- property 可以给属性赋值 实质是利用set方法给属性赋值 -->
<property name="str" value="Spring"/>
</bean>
(3)编写测试类
public class MyTest {
public static void main(String[] args) {
// 获取Spring的上下文对象
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
// 对象都在Spring中管理,要使用直接取出来就可以
Hello hello=(Hello)context.getBean("hello");
System.out.println(hello.toString());//输出:Hello{Str='Spring'}
}
}
(4)运行结果
4.IOC创建对象(创建bean)的方式
4.1使用无参构造创建默认
public User() {
System.out.println("User的无参构造");
}
public User(String name) {
this.name = name;
}
public class MyTest {
public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext("beans.xml");
User user=(User)context.getBean("user");
user.show();
}
}
4.2假设我们要用有参构造创建
4.2.1下标赋值
<bean id="hello" class="com.kuang.pojo.User">
<property name="name" value="姓名" />
</bean>
4.2.3类型赋值
<bean id="user" class="com.kuang.pojo.User">
<constructor-arg type="java.lang.String" value="444"/>
</bean>
4.2.3参数名赋值
<bean id="hello" class="com.kuang.pojo.User">
<property name="name" value="姓名" />
</bean>
4.2.4测试类
public class MyTest {
public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext("beans.xml");
User user=(User)context.getBean("user");
user.show();
}
}
总结:在配置文件加载的时候,容器中管理的对象就已经初始化了
5.Spring配置
5.1别名
<alias name="user" alias="username"/>
5.2 Bean的配置
<!--
1.id:bean的唯一标识,相当于对象名
2.class:bean对象的全限定名:包名+类型
3.name:也是别名,且name可同时起多个别名,可以用逗号,分号,空格隔开
-->
<bean id="user1" class="com.kuang.pojo.User" name="user2,u1">
<property name="name" value="西部开发"/>
</bean>
5.3import
impot一般用于团队开发 可以将多个配置文件导入合并一个
import
团队的合作通过import来实现 .
<import resource="{path}/beans.xml"/>
6.依赖注入
6.1构造器注入
我们在之前的案例已经讲过了
6.2 Set 注入 (重点)
要求被注入的属性 , 必须有set方法 , set方法的方法名由set + 属性首字母大写 , 如果属性是boolean类型 , 没有set方法
- 依赖注入:set注入
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象的所有属性,有容器注入
【环境搭建】
6.2.1.复杂类型
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
6.2.2.真实测试对象
public class User1 {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public User1() {
}
public User1(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User1{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
6.2.3.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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">]
<bean class="com.kuang.pojo.User1" p:name="狂神" p:age="18" scope="singleton"/>
</beans>
6.2.4.测试类
public class MyTest {
public static void main(String[] args) {
ApplicationContext context= new ClassPathXmlApplicationContext("bean.xml");
User user=(User)context.getBean("User");
System.out.println(user.getName());
System.out.println(user.getAddress());
}
}
6.3 C命名和P命名注入
6.3.1使用
<?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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="com.kuang.pojo.Student" p:name="胡少林" p:age="21" />
<bean id="user2" class="com.kuang.pojo.Student" c:age="18" c:name="狂神"/>
</beans>
6.3.2测试
@Test
public void test2(){
ApplicationContext context= new ClassPathXmlApplicationContext("UserBean.xml");
Student student=context.getBean("user2", Student.class);
System.out.println(student);
}
注意:P命名空间和C命名空间不能直接使用,需要导入xml约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
6.4bean的作用域
1.单例模式(Spring默认机制)
<bean id="user1" class="com.kuang.pojo.User1" p:name="狂神" p:age="18" scope="singleton"/>
@Test
public void test01(){
ApplicationContext context=new ClassPathXmlApplicationContext("User1Bean.xml");
User1 user1=context.getBean("user1",User1.class);
User1 user2=context.getBean("user1",User1.class);
System.out.println(user1==user2);
}
2.原型模式:每次从容器中get的时候,都会产生一个新对象
<bean id="accountServices" class="com.kuang.pojo.Student" scope="prototype"></bean>
@Test
public void test02(){
ApplicationContext context=new ClassPathXmlApplicationContext("UserBean.xml");
Student student1=context.getBean("student1",Student.class);
Student student2=context.getBean("student2",Student.class);
System.out.println(student1==student2);
}
3.其余的request、session、applcation只能在web开发中使用
7.bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式
- Spring会在上下文中自动寻找,并自动给bean装配属性
在Spring中有三种装配的方式
1.在xml中显式配置
2.在java中显式配置
3.隐式的自动装配【重要】
7.1 测试
一个人有两个宠物
1 cat.java
public class Cat {
public void shout(){
System.out.println("喵喵喵");
}
}
2 dog.java
public class Dog {
public void shout(){
System.out.println("汪汪汪");
}
}
3.person.java
public class Person {
private String name;
private Cat cat;
private Dog dog;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", cat=" + cat +
", dog=" + dog +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
}
7.2 ByName装配
会自动在容器上下文中查找,和自己对象set方法后面对应的beanid
7.2.1 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="cat" class="com.kuang.pojo.Cat"/>
<bean id="dog" class="com.kuang.pojo.Dog"/>
<!-- <bean id="people" class="com.kuang.pojo.Person">-->
<!-- <property name="name" value="人名"/>-->
<!-- <property name="cat" ref="cat"/>-->
<!-- <property name="dog" ref="dog"/>-->
<!-- </bean>-->
<!-- 注释的部分与上面代码作用相同 -->
<bean id="people" class="com.kuang.pojo.Person" autowire="byName">
<property name="name" value="胡少林"/>
</bean>
</beans>
7.2.2 测试方法
public class MyTest {
@Test
public void test01(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Person person=context.getBean("people",Person.class);
person.getDog().shout();
person.getCat().shout();
}
}
7.2.3 运行结果
7.3 ByType装配
会自动在容器上下文中查找和自己对象属性类相同的bean
7.3.1 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="cat" class="com.kuang.pojo.Cat"/>
<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="dog1" class="com.kuang.pojo.Dog"/>
<bean id="people" class="com.kuang.pojo.Person" autowire="byType">
<property name="name" value="胡少林"/>
</bean>
</beans>
7.3.2 测试方法
@Test
public void test01(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Person person=context.getBean("people",Person.class);
person.getDog().shout();
person.getCat().shout();
System.out.println(person.toString());
}
7.3.3 运行结果
7.3.4 结果分析
执行
<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="dog1" class="com.kuang.pojo.Dog"/>
<bean id="people" class="com.kuang.pojo.Person" autowire="byType">
<property name="name" value="胡少林"/>
</bean>
时 bytype会有两个dog 编译器不知道是哪个dog所以会报错
7.4 ByName和ByType的区别
- byname需要保证bean的id唯一,并且这个bean需要和自动注入属性的set方法的值一致
- bytype需要保证bean的class唯一,并且这个bean需要和自动注入属性的类型一致
7.5 使用注解实现自动装配
步骤
-
导入约束:xmlns:context=“http://www.springframework.org/schema/context”
-
配置注解的支持: context:annotation-config/
<?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/> </beans>
7.5.1 @Autowired
直接在属性上使用即可!也可在set方法上使用!
使用Autowired我们可以不编写Set方法,前提是其自动装配属性在IOC(Spring)容器中存在,且符合名字ByName
科普:
//@Nullable 字段标志了这个字段 表示这个字段可以为空 public Person(@Nullable String name) {//表示name字段可以为空,即name为空不报错 this.name = name; } //如果显式定义了 Autowired 的required属性为flase说明这个对象可以为空
@Autowired注解
@Autowired(required = false)//表示该子对象可以为空
private Cat cat
如果@Autowired自动装配的环境比较复杂,自动装配通过一个注解【@Autowired】完成的时候,我们可以使用@QUalifier(value="xxx"去配置@Autowired的使用,指定一个唯一的bean对象注入
7.5.2 @Rescourse注解
public class people{
@Rescourse(name="cat2")
private Cat cat;
@Rescourse
private Dog dog;
}
7.5.3 @Autowired注解与 @Rescourse注解
-
都是用来自动装配的,都可以放在字段是
-
@Rescourse注解默认通过ByName方式实现,如果找不到名字,则通过ByType实现!如果两个都找不到,就会报错
-
@Autowired注解通过ByName方式实现,而且必须要求对象存在 【常用】
-
执行顺序不同
7.5.4 @Nullable注解
如果一个字段用了@Nullable注解说明该字段可以为空
7.5.5@Component :组件,
放在类上,说明这个类被Spring管理
1.实体类加@Component注解
@Component//等价于<bean id="user" class="com.kuang.pojo.User"/> public class User { public String name="姓名"; }
2.在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 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.kuang.pojo"/> <!-- 开启注解支持 --> <context:annotation-config/> <!-- <bean id="user" class="com.kuang.pojo.User"/>--> </beans>
3.测试类
public class Test { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("applacationContext.xml"); User user=(User)context.getBean("user"); System.out.println(user.name); } }
4.运行结果
8.使用注解开发
在spring4之后,使用注解开发,必须要保证apo的包导入了
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.4</version>
</dependency>
使用注解需要导入Context约束
8.1bean
8.2属性如何注入
@Component//等价于<bean id="user" class="com.kuang.pojo.User"/>
public class User {
public String name;
@Value("狂神") //相当于<property name="name" value="kuangshen"/>
public void setName(String name) {
this.name = name;
}
}
8.3衍生的配置
@Component有几个衍生注解,我们在web开发中,会按照MVC三层架构分层!
-
dao层 【@Respositry】
-
service【@Service】
-
control层【@Controller】
这四个注解功能一样,都是将某个类注册的Spring中,装配Bean
8.4自动装配
- @Autowired: 自动装配 通过类型、名字
如果Autowired不能唯一自动装配上属性,则需要通过@Qualifer(value=="xxx")
- @Nullable:字段标记了这个注解,这个字段可以为null
- @Resource : 字段装配通过名字、类型
8.5 作用域
@Component//等价于<bean id="user" class="com.kuang.pojo.User"/>
@Scope("prototype")//作用域
public class User {
//public String name="姓名";
public String name;
@Value("狂神") //相当于<property name="name" value="kuangshen"/>
public void setName(String name) {
this.name = name;
}
}
8.6 小结
8.6.1 xml与注解:
- xml更加万能,适用于任何场合,维护简单方便
- 注解不是自己的类使用不了,维护相对复杂
8.6.2 xml与注解最佳实践
- xml用来管理bean
- 注解只负责完成属性的注入
- 在使用的过程中,只需要注意 让注解生效 要开启注解支持
<!-- 扫描机制
指定要扫描的包,这个包下的注解就会生效
-->
<context:component-scan base-package="com.kuang"/>
<!-- 开启注解支持 -->
<context:annotation-config/>
9.使用java的方式配置Spring
完全不使用xml配置 完全交给Java来做
javaConfig是Spring的一个子项目
9.1 编写实体类User.java
package com.kuang.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//这个注解说明这个类被Spring接管(注册到容器中)
@Component
public class User {
private String name;
public User() {
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
@Value("名字")//属性注入值
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
9.2 编写配置类config.java 配置spring
package com.kuang.config;
import com.kuang.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
//这个也会Spring容器托管,注册到容器中,因为他本来就是一个@Compment
@Configuration
@ComponentScan("com.kuang.pojo")
@Import(KuangConfig2.class)
public class KuangConfig {
// 注册一个Bean 相当于Bean标签
// 这个方法的名字 相当于Bean标签中的id属性
// 这个方法的返回值,相当于Bean标签中的class属性
@Bean
public User getUser(){
return new User(); //就是返回值要注入Bean对象
}
}
9.3 编写测试类 MyTest.java
public class MyTest {
// 如果完全使用配置方式去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载
public static void main(String[] args) {
ApplicationContext context= new AnnotationConfigApplicationContext(KuangConfig.class);
User user=(User)context.getBean("getUser");//方法名
System.out.println(user.getName());
}
}