Spring学习笔记

Spring

Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架

程序员不用管理对象的创建,使系统的耦合性大大降低,可以更加专注的在业务的实现上。这就是IoC的原型!

1、Spring IoC 创建对象方式

<!--方式一,通过property给属性赋值-->
<bean id="user" class="com.jerry.pojo.User">
    <property name="name" value="test 03" />
</bean>

<!--构造器方法创建bean实例-->
<!--方式二,索引下标赋值-->
<bean id="user" class="com.jerry.pojo.User">
    <constructor-arg index="0" value="ceshi" />
</bean>

<!--方式三,通过类型创建,不建议使用-->
<bean id="user" class="com.jerry.pojo.User">
    <constructor-arg type="java.lang.String" value="mingzi" />
</bean>

<!--方式四,直接通过参数名称给参数赋值-->
<bean id="user" class="com.jerry.pojo.User">
    <constructor-arg name="name" value="jiushi" />
</bean>

2、Spring 配置

2.1、别名(Alias)

  • Alias 取别名
<!--别名Alias,如果添加了别名,我们也可以使用别名获取到这个对象-->
<alias name="user" alias="bieming"/>
  • name 也是别名,而且name 可以同时取多个别名
<bean id="user" class="com.jerry.pojo.User" name="user2,user3,shiti">
    <constructor-arg name="name" value="jiushi" />
</bean>

2.2、Bean的配置

<!--bean
id: bean 的唯一标识
class: 被装配成Bean的实体类
name: 也是别名,且可以同时取多个别名
-->
<bean id="hello" class="com.jerry.pojo.Hello">
    <property name="name" value="Spring" />
    <property name="pwd" value="1234" />
</bean>

2.3、import

一般用于团队开发使用的,他可以将多个配置文件,导入合并为一个

只要在主要的配置文件中,导入其他的配置文件

<import resource="bean.xml" />

最后只要使用总的配置之后就可以了

3、依赖注入DI

3.1、构造器注入

<!--构造器方法创建bean实例-->
<!--方式二,索引下标赋值-->
<bean id="user" class="com.jerry.pojo.User">
    <constructor-arg index="0" value="ceshi" />
</bean>

<!--方式三,通过类型创建,不建议使用-->
<bean id="user" class="com.jerry.pojo.User">
    <constructor-arg type="java.lang.String" value="mingzi" />
</bean>

<!--方式四,直接通过参数名称给参数赋值-->
<bean id="user" class="com.jerry.pojo.User">
    <constructor-arg name="name" value="jiushi" />
</bean>

3.2、set方式注入

  • 依赖注入
    • 依赖:bean随想的创建依赖于容器
    • 注入:bean对象的所有属性,有容器来注入

POJO

  • Address
package com.jerry.pojo;

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Address{" +
                "address='" + address + '\'' +
                '}';
    }
}
  • Student
package com.jerry.pojo;

import java.util.*;

public class Student {

    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbies;
    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> getHobbies() {
        return hobbies;
    }

    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }

    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) +
                ", hobbies=" + hobbies +
                ", card=" + card +
                ", games=" + games +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }
}

配置类

<?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.jerry.pojo.Address"/>

    <bean id="student" class="com.jerry.pojo.Student">
        <!--第一种,普通注入方式,value-->
        <property name="name" value="jerry"/>
        <!--第二种,Bean注入,ref-->
        <property name="address" ref="address"/>
        <!--数组-->
        <property name="books">
            <array>
                <value>java</value>
                <value>python</value>
                <value>php</value>
                <value>go</value>
                <value>swift</value>
            </array>
        </property>
        <!--List-->
        <property name="hobbies">
            <list>
                <value></value>
                <value></value>
            </list>
        </property>
        <!--map-->
        <property name="card">
            <map>
                <entry key="idCard" value="123456875"/>
                <entry key="zhaohang" value="622582635"/>
            </map>
        </property>
        <!--set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>CF</value>
                <value>DNF</value>
            </set>
        </property>

        <!--null-->
        <property name="wife">
            <null></null>
        </property>

        <!--Properties-->
        <property name="info">
            <props>
                <prop key="学号">202001</prop>
                <prop key="姓名">jerry</prop>
            </props>
        </property>
    </bean>
</beans>

测试类

import com.jerry.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.toString());
    }
}

测试结果

Student{
name='jerry', 
address=Address{address='null'}, 
books=[java, python, php, go, swift], 
hobbies=[打, 做], 
card={
idCard=123456875, 
zhaohang=622582635
}, 
games=[LOL, CF, DNF], 
wife='null', 
info={学号=202001, 姓名=jerry}
}

3.3、拓展方式注入

3.3.1、p 命名空间

实体类

package com.jerry.pojo;

public class User {
    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;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

配置类

<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--p命名空间注入,可以直接注入属性的值,property-->
    <bean id="user" class="com.jerry.pojo.User" p:name="jerry" p:age="3"/>
</beans>

测试类

@Test
public void Test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("UserBeans.xml");
    User user = context.getBean("user",User.class);
    System.out.println(user.toString());
}
3.3.2、c 命名空间

实体类中添加有参和无参构造

public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

配置类中添加 c 命名空间

xmlns:c="http://www.springframework.org/schema/c"

<!--c命名空间注入,相当于构造器方法注入属性,construct-arg-->
    <bean id="user2" class="com.jerry.pojo.User" c:name="c-name" c:age="5"/>

3.4、Bean的作用域

ScopeDescription
singleton(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
prototypeScopes a single bean definition to any number of object instances.
requestScopes 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
sessionScopes a single bean definition to the lifecycle of an HTTP . Only valid in the context of a web-aware Spring .Session``ApplicationContext
applicationScopes a single bean definition to the lifecycle of a . Only valid in the context of a web-aware Spring .ServletContext``ApplicationContext
websocketScopes a single bean definition to the lifecycle of a . Only valid in the context of a web-aware Spring .WebSocket``ApplicationContext
  • 单例模式(singleton)【默认】
    在这里插入图片描述

  • 原型模式(prototype)

在这里插入图片描述

每次从原型中get的时候,都会产生一个新的对象

==本质区别:==单列模式只是在内存空间中创建了一个Bean实例,而原型模式是创建了多个内容相同的Bean实例,每个实例的内存空间地址不一样

4、自动装配

  • 自动装配是Spring满足bean依赖一种方式!
  • Spring会在上下文中自动寻找,并自动给bean 装配属性

在Spring中有三种装配方式

1.在xml中显示的配置

<bean id="dog" class="com.jerry.pojo.Dog" />
<bean id="cat" class="com.jerry.pojo.Cat" />

<bean id="people" class="com.jerry.pojo.People">
    <property name="name" value="jerry"/>
    <property name="cat" ref="cat"/>
    <property name="dog" ref="dog"/>
</bean>

2.在java中显示配置

3.隐式的自动装配bean【*】

4.1、byName自动装配

  • 会自动在容器上下文中查找,和自己的对象set方法后面的值对应的beanid!
<!--自动装配,byName-->
<bean id="dog" class="com.jerry.pojo.Dog" />
<bean id="cat" class="com.jerry.pojo.Cat" />

<bean id="people" class="com.jerry.pojo.People" autowire="byName">
    <property name="name" value="jerry"/>
</bean>

4.2、byType自动装配

  • 会自动在容器上下文中查找,和自己的对象属性类型相同的bean!
<bean id="dog" class="com.jerry.pojo.Dog" />
<bean id="cat2" class="com.jerry.pojo.Cat" />

<bean id="people" class="com.jerry.pojo.People" autowire="byType">
    <property name="name" value="jerry"/>
</bean>
  • Attention:

byName 需要保证 bean 的 id 唯一,并且这个 bean 需要和自动注入的属性的 set 方法的值一致

byType 需要保证所有 bean 的 class 唯一,并且这个 bean 需要和西东注入的属性的类型一致

4.3、注解实现自动装配

使用注解步骤

​ 1、在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:annotation-config/>

</beans>

​ 2、配置注解的支持 context:annotation-config/

添加@Autowired 注解支持,就可以自动装配 了

public class People {
    private String name;
    @Autowired
    private Cat cat;
    @Autowired
    private Dog dog;
}

拓展:

@Nullable 	//此注解标记的字段可以为空

@Autowired
@Qualifier(value=“xxx”) //这两个注解配合使用,可以显示指定Bean容器【自动装配环境比较复杂的时候可以使用】

public class People {
    private String name;
    @Autowired
    @Qualifier(value = "cat2")
    private Cat cat;
    @Autowired
    private Dog dog;
}

@Resource 也可以实现自动装配,且不需要spring框架的支持

public class People {
    private String name;
    @Resource
    private Cat cat;
    @Resource
    private Dog dog;
}

@Resource 和 @Autowired 区别:

  • 都是通过自动装配的,都可以放在属性的字段上
  • @Autowired 通过byName 的方式实现,而且必须要求这个对象的存在
  • @Resource默认通过byName方式实现,如果找不到名字,则通过byType实现,如果都找不到,则报错!

5、使用注解开发

使用注解开发,需要保证 aop 依赖包已经成功导入
在这里插入图片描述
配置注解的支持 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>

注解说明:

  • @Component

组件,放在类上,说明这个类已被spring管理了

<!--指定要扫描的包马,使得这个包下的注释会生效-->
<context:component-scan base-package="com.jerry.pojo" />
@Component
public class User {
    public String name = "jerry";
}
  • @Value

指定属性的具体值,相当于 xml 中的 property 赋予属性值的操作

@Component
public class User {
    @Value("jerry")
    public String name;
}

@Component 衍生的注解(一下的功能都是一样的,都是交由Spring进行托管)

​ dao 【@Repository】

​ service 【@Service】

​ controller 【@Controller】

  • @Scope

作用域,可以指定单例模式【singleton】和原型模式【prototype】

6、java配置注解

所有的配置将全部交由java来自定义实现

  • 创建MyConfig类
@Configuration
public class MyConfig {
        //注册一个Bean,相当于在xml中的<bean/>标签,这个方法的名字就是bean标签中的id,方法的返回值就是bean标签中的class属性
    @Bean
    public User user(){
        return new User();
    }
}

@Configuration 代表这是一个配置类,其本质就是一个component

  • pojo
@Component
public class User {
    private String name;

    public String getName() {
        return name;
    }

    @Value("jerry")
    public void setName(String name) {
        this.name = name;
    }
}
  • 测试
public class MyTest {
    @Test
    public void test1(){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User user = (User) context.getBean("user");
        System.out.println(user.getName());
    }
}

7、AOP

AOP (Aspect Oriented Programming,面向切面编程),通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。

7.1、使用Spring的API接口
  • 导入aop依赖(织入包)
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.6</version>
    <scope>runtime</scope>
</dependency>
  • 创建接口个和实现类
public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void select();
}
public class UserServiceImpl implements UserService {
    public void add() {
        System.out.println("add a user!");
    }

    public void delete() {
        System.out.println("delete a user!");

    }

    public void update() {
        System.out.println("update a user!");

    }

    public void select() {
        System.out.println("query a user!");
    }
}
  • 创建切入点(日志)类
package com.jerry.log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class Log implements MethodBeforeAdvice {
    //method: 将要执行的目标对象的方法
    //args: 参数
    //target:目标对象
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass()+"将要执行"+method.getName()+"方法");
    }
}
package com.jerry.log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {
    //returnValue:返回值
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass()+"执行了"+method.getName()+"方法,返回值是"+returnValue);
    }
}
  • 配置文件
<?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-->
    <bean id="userService" class="com.jerry.service.UserServiceImpl"/>
    <bean id="log" class="com.jerry.log.Log"/>
    <bean id="afterLog" class="com.jerry.log.AfterLog"/>

    <!--配置aop-->
    <aop:config>
        <!--切入点:expression:表达式;execution:要执行位置-->
        <aop:pointcut id="pointcut" expression="execution(* com.jerry.service.UserServiceImpl.*(..))"/>

        <!--执行环绕增加-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>

</beans>
  • 测试类
import com.jerry.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        //动态代理的对象是"接口"
        UserService userService = (UserService) context.getBean("userService");
        userService.add();
        userService.select();
    }
}

7.2、自定义类实现

  • 自定义切入点类
package com.jerry.diy;

public class DiyPointCut {
    public void before(){
        System.out.println("==================before===================");
    }

    public void after(){
        System.out.println("==================after===================");
    }
}
  • 配置文件
<!--方式二:自定义类-->
<bean id="diy" class="com.jerry.diy.DiyPointCut"/>
<aop:config>
    <!--自定义切面,ref指向对应的类-->
    <aop:aspect ref="diy">
        <!--切入点-->
        <aop:pointcut id="point" expression="execution(* com.jerry.service.UserServiceImpl.*(..))"/>
        <!--通知-->
        <aop:before method="before" pointcut-ref="point"/>
        <aop:after method="after" pointcut-ref="point"/>
    </aop:aspect>
</aop:config>

7.3、使用注解方式实现AOP

  • 导入注解依赖
<dependency>
    <groupId>aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.5.4</version>
</dependency>
  • 创建注解自定义类
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class AnnotationPointCut {
    @Before("execution(* com.jerry.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("======before=====");
    }

    @After("execution(* com.jerry.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("======after======");
    }

    //在环绕增强中,我们可以定义一个参数,代表我们要获取处理切入的点
    @Around("execution(* com.jerry.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("===环绕前===");
        //获得签名
        Signature signature = joinPoint.getSignature();
        System.out.println("signature:"+signature);
        //执行方法
        Object proceed = joinPoint.proceed();
        System.out.println("===环绕后===");
        System.out.println(proceed);
    }
}
  • 配置文件
<!--方式三:使用注解实现AOP-->
<bean id="annotationPointCut"  class="com.jerry.diy.AnnotationPointCut"/>
<!--开启注解支持-->
<aop:aspectj-autoproxy/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值