狂神说Java-Spring笔记

1.环境搭建

maven搭建一个干净的项目,不使用任何模板

//导入这个包可以同时导入大量其依赖的包,简单
 <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>

2.控制反转

  • 控制翻转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式,在Spring中实现控制反转的是IoC容器,其实现方式是依赖注入(Dependency Injection
    讲人话就是:需要对象不用自己手动去创建,Spring帮你来创建,管理,装配。
  • 当需要修改时,只需要修改beans.xml中标签的属性值,不用去修改代码。
2.1 第一个spring程序

1.实体类Hello


public class Hello {
    private String str;
    public String getStr() {
        return str;
    }
    public void setStr(String str) {
        this.str = str;
    }
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

2.配置文件beans.xml:其中bean标签中的id值相当于对象名class的值表示要new的类property标签表示给对象中的属性property设置一个值value
如果property的值的类型是一个对象,可以使用ref,表示引用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="hello" class="pojo.Hello">
        <property name="str" value="Hello Spring"/>
    </bean>
</beans>

3.测试类:ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");这句话表示拿到spring容器,然后用context.getBean("id")来获取对象,而不用去new


public class MyTest {
    public static void main(String[] args) {
        //输入new CPX ,按alter+enter快捷生成
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}
2.2 IoC创建对象的方式

1.默认使用无参构造方法创建对象
2.当使用有参构造时,有三种方法

在配置文件加载的时候,容器中管理的对象就已经初始化了

3.依赖注入(重点)

依赖:bean对象的创建依赖于容器!
注入:bean对象中的所有属性,由容器来注入!

3.1 构造器注入
//实体类
public class User{
public User(String name){
	this.name=name;
	}
//get(),set(),toString()省略
}
  • 通过参数下标:一个参数的下标为0
<bean id="user" class="pojo.User">
	<constructor-arg index="0" value="zhongliwen"/>
</bean>
  • 通过参数类型(多个参数相同类型会出问题,不建议使用)
<bean id="user" class="pojo.User">
	<constructor-arg type="java.lang.String" value="zhongliwen"/>
</bean>
  • 通过参数名(建议使用)
<bean id="user" class="pojo.User">
	<constructor-arg name="name" value="zhongliwen"/>
</bean>
3.2 set方式注入(重点)

实体类Student

private String name;
private Address address; //Address为一个类,里面一些属性
private String[] books;
private List<String> hobbies;
private Map<String,String> card;
private Set<String> games;
private Properties info;
private String wife;

配置文件beans.xml(重点)

//注册Address实体类
<bean id="addr" class="pojo/Address"/>
//注册Student实体类
<bean id="student" class="pojo/Student">
	<property name="name" value="Lewis"/>//普通值,用value
    <property name="address" ref="addr"/>//对象,用ref,与上面的地址bean的id值相同
    <property name="books">		//数组注入
    	<array>
    		<value>红楼梦</value>
    		<value>西游记</value>
    		<value>三国演义</value>
    	</array>
    </property>
    <property name="hobbies">	//List注入
    	<list>
    		<value>听歌</value>
    		<value>敲代码</value>
    		<value>看电影</value>
    	</list>
    </property>
    <property name="card">	//Map注入	
    	<map>
    		<entry key="身份证" value="4306XXXXXXXX"/>
    		<entry key="银行卡" value="1903XXXXXXXX"/>
    	</map>
   </property>
   <property name="games">	//Set注入
    	<set>
    		<value>LOL</value>
    		<value>DNF</value>
    		<value>CS</value>
    	</set>
   </property>
    <property name="info">		//properties资源文件注入
    	<props>
    		<prop key="url">jdbc:mysql://localhost:3306</prop>
    		<prop key="name">root</prop>
    		<prop key="password">123456</prop>
    	</props>
    </property>					//null注入
    <property name="wife">
    	<null/>
    </property>

3.3 C、P命名空间注入(了解)

首先需要在beans.xml文件下的beans标签中导入C、P的XML约束

xmls:c="http://www.springframework.org/schema/c"
xmls:p="http://www.springframework.org/schema/p"

其中,C对应有参构造,P对应set注入,是他们的简化版

<bean id="user" class="pojo/User" c:name="Lewis"/>
<bean id="user" class="pojo/User" p:name="Lewis"/>

4.bean

4.1bean的作用域

1.单例模式:<bean id="" class="" scope="singleton"/>
Spring默认机制,一个类只实例化一次,通过get方法得到的对象,即使对象的名字不同,本质还是同一个
2.原型模式:<bean id="" class="" scope="prototype"/>
每次从容器中get时,都会产生一个新对象!适用于多线程
3.其余的request,session,application,只能在web开发中使用到,表示对象的生存周期

4.2 bean的自动装配

实体类People,有两个宠物Cat,Dog

public class People{
	private String name;
	private Cat cat;	//猫,狗的实体类省略,知道是一个对象类型就行
	private Dog dog;
	//setDog(),setCat(),getDog(),getCat(),toString()方法省略
}
  • byName自动装配:会自动在容器上下文中查找和people对象set方法后面的值对应的bean的id。如People实体类中有一个setDog方法,且beans.xml文件中有一个id值为dog的bean,因此people bean中可以省略dogproperty,会自动注入。
    简单来说就是:实体类有setDog方法,beans.xml中有id="dog"bean,省略dog property
<bean id="cat" class="pojo/Cat"/>
<bean id="dog" class="pojo/Dog"/>
<bean id="people" class="pojo/People" autowire="byName">
	<property name="name" value="Lewis"/>
	//<property name="cat" ref="cat"/>自动装配会自动完成,这两行代码可以省略
	//<property name="dog" ref="dog"/>
</bean>
  • byType自动装配:自动在容器中查找和自己对象类型相同的bean(同一个pojo中)

小结
byName的时候,需要保证所有bean的id唯一,并且这个id要和自动注入的属性的set方法的值一致!
byType的时候,需要保证所有的bean的class唯一,并且这个bean的属性要和自动注入的属性类型一致!

5 注解开发

1.在xml配置文件中的beans标签中加入注解支持

<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"
>

2.开启注解支持

<context:annotation-config/>
<context:component-scan base-package="pojo"/>

3.注解使用:自动装配

  • @Autowired:先通过类型,再通过名字,用在对象属性上
  • @resource:先通过名字,再通过类型,用在对象属性上
  • @Component:对整个类进行装配。衍生出@Respository,@Service,@Controller,分别用在Dao层、Service层、Controller层的类上,效果一样。所有属性不用写get/set方法
  • @Value:用在属性上,给属性赋值

小结:

  • XML更加万能,适用于任何场合,维护简单方便!
  • 注解不是自己的类使用不了,维护相对复杂
  • xml用来管理bean,注解只完成属性的注入。

6.使用JavaConfig实现配置

使用一个JavaConfig类,来替代原来的beans.xml

@Configuration
@ComponentScan("pojo")
//这个类也会被注入到Spring容器中,其本质就是一个@Component
//@Configuration代表这是一个配置类,用于替代beans.xml
public class LewisConfig {
    @Bean
    //注册一个bean,相当于xml里的一个bean标签
    //方法的名字相当于bean标签的id值
	//方法的返回类型相当于bean标签的class属性值
    public User getUser(){
        return new User();
    }
}

使用下面的代码来获得Spring容器,同样用getBean方法来获得容器中的对象

ApplicationContext context = new AnnotationConfigApplicationContext(LewisConfig.class);

7.面向切面编程AOP(重点)

  • 横切关注点:横跨多个模块的方法或功能,待加入到业务层实现功能扩充,如日志功能
  • 切面(aspect):横切关注点被模块化的特殊对象,是一个类,即下文中的afterLog
  • 通知(advice):切面必须完成的工作,即类中的一个方法
  • 目标(target):被通知对象,下文中的UserServiceImpl类的对象
  • 代理(proxy):向目标对象加入通知创建的新对象
  • 切入点(pointcut):切面通知执行的“地点”的定义
  • 连接点(jointpoint):与切入点匹配的执行点
7.1 Spring API接口实现

在保持service层代码不变的基础上,通过AOP新增一些其他的功能。
目录结构树如下
在这里插入图片描述

//UserService接口
public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void select();
}
//UserServiceImpl实现类
public class UserServiceImpl implements UserService{
    public void add() {
        System.out.println("增加了一个用户");
    }

    public void delete() {
        System.out.println("删除了一个用户");
    }

    public void update() {
        System.out.println("修改了一个用户");
    }

    public void select() {
        System.out.println("查询了一个用户");
    }
}
//afterLog
public class afterLog  implements AfterReturningAdvice {
    public void afterReturning(Object returnValue, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法,返回的结果为"+returnValue);
    }
}
//beforeLog
public class beforeLog implements MethodBeforeAdvice {
    public void before(Method method, Object[] objects, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--    注册bean-->
    <bean id="userService" class="com.lewis.service.UserServiceImpl"/>
    <bean id="afterLog" class="com.lewis.log.afterLog"/>
    <bean id="beforeLog" class="com.lewis.log.beforeLog"/>

    <aop:config>
        <aop:pointcut id="pointcup" expression="execution(* com.lewis.service.UserServiceImpl.*(..))"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcup"/>
        <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcup"/>
    </aop:config>
</beans>
7.2自定义实现AOP(主要是切面定义)推荐使用

目录树
在这里插入图片描述
自定义接口类

public class DiyPointCut {
    public void before(){
        System.out.println("===========方法执行前================");
    }
    public void after(){
        System.out.println("===========方法执行后================");
    }
}

配置文件

<bean id="diy" class="diy.DiyPointCut"/>
<aop:config>
    <!--切面:一个类-->
    <aop:aspect ref="diy">
    <!--切入点-->
        <aop:pointcut id="point" expression="execution(* service.UserServiceImpl.*(..))"/>
    <!--通知-->
        <aop:after method="after" pointcut-ref="point"/>
        <aop:before method="before" pointcut-ref="point"/>
    </aop:aspect>
</aop:config>
7.3使用注解实现AOP

在类上使用@Aspect,表明这个类是一个切面;在方法上使用@Before,@After等实现通知
在这里插入图片描述

<bean id="annotationPointCut" class="service.UserServiceImpl"/>
<!--开启注解支持-->
<aop:aspectj-autoproxy/>
@Aspect
public class AnnotationPointCut {
    @Before("execution(* service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("===========方法执行前===========");
    }
    @After("execution(* service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("===========方法执行后===========");
    }
     @Around("execution(* service.UserServiceImpl.*(..))")
    public void around(){
        System.out.println("===========环绕后===========");
    }
}

around的优先级高于before,after

  • 7
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值