Spring学习

Spring优点

Spring是一个开源免费的框架(容器)
Spring是一个轻量级的,非入侵式框架
控制反转(IOC)、面向切面(AOP)
支持事务的处理,对框架整合的支持

IOC控制反转

public interface UserDao {
    void getUser();
}

public class UserDaoImpl implements UserDao {
    public void getUser() {
        System.out.println("User");
    }
}

public class UserDao01Impl implements UserDao {
    public void getUser() {
        System.out.println("User1");
    }
}

public class UserDao02Impl implements UserDao {
    public void getUser() {
        System.out.println("User2");
    }
}

public interface UserService {
    void getUser();
}

public class UserServiceImpl implements UserService {
    private UserDao userDao;

    //利用set进行动态实现值的注入
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void getUser() {
        userDao.getUser();

    }
}

public class MyTest {
    public static void main(String[] args) {
        //原始方法中用户实际调的是业务层,dao层不需要接触
        UserService userService = new UserServiceImpl();
        ((UserServiceImpl) userService).setUserDao(new UserDao01Impl());//控制反转
        userService.getUser();

    }
}

在dao层修改代码后,不需要改变service层代码去管理对象的创建,直接利用set方法想使用哪个接口就使用哪个,就是IOC原型,大大降低系统耦合性。

IOC创建对象

使用无参构造创建对象,默认方法。
使用有参构造创建对象。

1.下标赋值

    <bean id="user" class="com.study.pojo.User">
        <constructor-arg index="0" value="下标赋值创建"/>
    </bean>

2.类型赋值

    <bean id="user" class="com.study.pojo.User">
        <constructor-arg type="java.lang.String" value="类型创建"/>
    </bean>

3.直接通过参数名创建

	<bean id="user" class="com.study.pojo.User">
        <constructor-arg name="name" value="参数名创建"/>
    </bean>

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

Spring配置

别名

<!--别名,如果添加了别名,也可以使用别名获取这个对象-->
    <alias name="user" alias="userPro"/>

Bean的配置

    <!--
    id:bean的唯一标识符,相当于对象名
    class:bean对象所对应的全限定名:包名+类名
    name:也是别名,而且可以同时取多个别名,可以识别不同的分隔符
    -->
        <bean id="user" class="com.study.pojo.User" name="u1 u2,u3;u4">
            <property name="name" value="标签"/>
        </bean>

import
一般用于团队开发,可以将多个配置文件导入合并为一个,相同的还会合并

    <import resource="applicationContext.xml"/>

DI依赖注入(三种方式)

1.构造器注入(上面的创建对象)
2.Set方式注入【重要】
依赖注入:就是Set注入
依赖:bean对象的创建依赖于容器
注入:bean对象中的所有属性,由容器来注入

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 + '\'' +
                '}';
    }
}
public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> cards;
    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> getHobbys() {
        return hobbys;
    }

    public void setHobbys(List<String> hobbys) {
        this.hobbys = hobbys;
    }

    public Map<String, String> getCards() {
        return cards;
    }

    public void setCards(Map<String, String> cards) {
        this.cards = cards;
    }

    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) +
                ", hobbys=" + hobbys +
                ", cards=" + cards +
                ", 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.study.pojo.Address">
        <property name="address" value="西安"/>
    </bean>

    <bean id="student" class="com.study.pojo.Student">
        <!--普通注入-->
        <property name="name" value="大头"/>
        <!--bean注入-->
        <property name="address" ref="address"/>
        <!--数组注入-->
        <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="cards">
            <map>
                <entry key="农行" value="12342423442342523"/>
                <entry key="招行" value="89088978732847324"/>
            </map>
        </property>
        <!--Set注入-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>IOC</value>
                <value>AOP</value>
            </set>
        </property>
        <!--null注入-->
        <property name="wife">
            <null></null>
        </property>
        <!--properties注入-->
        <property name="info">
            <props>
                <prop key="性别"></prop>
                <prop key="爱好"></prop>
            </props>
        </property>
    </bean>
</beans>
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='大头',
         * address=Address{address='西安'},
         * books=[西游记, 水浒传, 红楼梦],
         * hobbys=[吃饭, 睡觉, 打豆豆],
         * cards={农行=12342423442342523,
         * 招行=89088978732847324},
         * games=[LOL, IOC, AOP],
         * wife='null',
         * info={性别=男, 爱好=女}}
         */

    }

}

3.拓展方式注入
可以使用p命名空间和c命名空间,需要导入xml约束,如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"//p命名空间
       xmlns:c="http://www.springframework.org/schema/c"//c命名空间
       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">

    <!--p命名空间可以直接注入属性,相当于property-->
    <bean id="user" class="com.study.pojo.User" p:name="大头" p:age="24"/>

    <!--c命名空间通过构造器注入,相当于constructor-arg-->
    <bean id="user2" class="com.study.pojo.User" c:name="小头" c:age="25"/>
</beans>

测试

@Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
        User user = (User) context.getBean("user2");
        System.out.println(user);
    }

bean的作用域

在这里插入图片描述
1.单例模式(默认方式scope=“singleton”)

    <bean id="user2" class="com.study.pojo.User" c:name="小头" c:age="25" scope="singleton"/>

测试:返回为true,用的是同一个对象

@Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
        User user = (User) context.getBean("user2");
        User user1 = (User) context.getBean("user2");
        System.out.println(user == user1);
    }

2.原型模式

<bean id="user2" class="com.study.pojo.User" c:name="小头" c:age="25" scope="prototype"/>

测试(同上):返回为false,每次产生新的对象
3.其他是在web项目中使用
reques请求创建完就失效
session一直在session中存在
application全局都存在

Bean的自动装配

自动装配是Spring满足bean依赖的一种方式(上面的算是手动装配)
Spring会在上下文中自动寻找,并自动给bean装配属性

Spring中有三种装配的方式

1.在xml中显示的配置
2.在Java中显示配置
3.隐式的自动装配bean【重要】
3.1 byName和byType自动装配
byName:会自动在容器上下文中查找与自己对象的set方法后面的值对应的bean id注入,且名字必须相同
byType:会自动在容器上下文中查找与自己对象的属性类型相等的bean注入,且类型必须唯一,因为根据类型所以有没有id都可以

<?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="cat" class="com.study.pojo.Cat"/>
    <bean id="dog" class="com.study.pojo.Dog"/>

<!--    <bean id="people" class="com.study.pojo.People">-->
<!--        <property name="cat" ref="cat"/>-->
<!--        <property name="dog" ref="dog"/>-->
<!--        <property name="name" value="大头"/>-->
<!--    </bean>-->
    <!--
    byName:会自动在容器上下文中查找与自己对象的set方法后面的值对应的bean id注入,且名字必须相同
    byType:会自动在容器上下文中查找与自己对象的属性类型相等的bean注入,且类型必须唯一,因为根据类型所以有没有id都可以
    -->
    <bean id="people" class="com.study.pojo.People" autowire="byName">
        <property name="name" value="大头"/>
    </bean>
</beans>

4.使用注解实现自动装配
使用注解须知
4.1导入约束:context约束
4.2配置注解的支持: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>

@Autowired
直接在属性上用,也可以在set方法上使用。
使用Autowired可以不用写set方法,前提是这个自动装配的属性在IOC(Spring)容器中存在,且符合byType的名字相同
不常用:
@Nullable 注解标记了这个字段,说明这个字段可以为null;
@Autowired(required = false) 如果定义了required的属性为false,说明这个对象可以为null,否则不允许为null;

如果@Autowired自动装配的环境比较复杂(有id不同的多个bean),自动装配无法通过一个注解去完成,我们可以增加@Qualifier(value=“xxx”)去配合@Autowired使用,指定一个唯一的bean注入,相当于使用byName。如下例子,指定注入id为cat11的bean。

    @Autowired
    @Qualifier(value = "cat11")
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog11")
    private Dog dog;
    private String name;

@Resource
1)两者都是用来自动装配的,都可以放在属性字段上,@Autowired是spring的,@Resource是Java中的。
2)@Autowired是通过byType的方式实现,必须要求这个对象存在,如果使用名字就加@Qualifier(value=“xxx”),用名字去装配。
3)@Resource默认通过byName的方式实现,如果找不到名字,则通过byType实现,如果俩个都找不到就报错。
4)执行顺序不同,@Autowired是先通过byType的方式实现,@Resource是先通过byName的方式实现。

使用注解开发

1.注入

<bean id = "user" class = "com.study.pojo.User" scope="prototype">
        <property name = "name" value = "大头"/>
    </bean>

相当于

//等价与<bean id = "user" class = "com.study.pojo.User"/>
//@Component 组件
@Component
@Scope("prototype")//对应配置文件中是单例还是原型模式
public class User {

    //相当于<property name = "name" value = "大头"/>
    @Value("大头")
    public String name;
}

2.衍生注解
@Component有几个衍生注解,在web开发中,会按照mvc架构分层
-dao【@Repository】
-service【@Service】
-controller【@Controller】
以上四个注解功能全部一样,都是代表将某个类注册到Spring中,装配Bean

使用Java配置Spring
//这个注解也是Spring管理的,注册到容器中,因为它本来也被@component注解
//@Configuration代表这是一个配置类,就是applicationContext.xml
@Configuration
@ComponentScan("com.study.pojo")//配置包扫描
public class MyConfig {

    //注册一个bean,相当于之前的bean标签
    //方法的名字相当于bean标志中的id属性
    //方法的返回值相当于bean标志中的class属性
    @Bean
    public User getUser(){
        return new User();//就是返回要注入bean的对象
    }
}

public class MyTest {
    public static void main(String[] args) {
        //如果完全使用配置类方式,就需要通过AnnotationConfigApplicationContext来获取容器
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User user = (User) context.getBean("getUser");
        System.out.println(user.getName());
    }
}

AOP

代理模式(AOP的底层)

静态代理
1)抽象角色:一般会使用接口或抽象类来解决
2)真是角色:被代理的角色
3)代理角色:代理真实角色,代理真是角色后,一般会做一些附属操作
4)客户:访问代理对象的人

//出租,抽象角色
public interface Rent {
    public void rent();
}
//房东,真实角色
public class Host implements Rent {
    public void rent() {
        System.out.println("房东出租房子");
    }
}
//代理,代理角色
public class Proxy implements Rent{
    private Host host;
    public Proxy() {
    }
    public Proxy(Host host) {
        this.host = host;
    }
    public void rent() {
        host.rent();
        seeHouse();
        hetong();
    }
    //看房
    public void seeHouse(){
        System.out.println("中介带你看房");
    }
    //签合同
    public void hetong(){
        System.out.println("中介带你签合同");
    }
}
//我,客户
public class Client {
    public static void main(String[] args) {
        Host host = new Host();
        Proxy proxy = new Proxy(host);
        proxy.rent();
    }
}

静态代理好处:
可以使真实角色操作更加纯粹,不用关注一下公共业务。
公共业务交给代理角色,实现业务分工。
公共业务发送扩展时候,方便集中管理。
缺点:一个真实角色就会产生一个代理角色,开发效率变低。

动态代理
1)动态代理和静态代理角色一样。
2)动态代理的代理类是动态生成的,不是我们直接写好的。
3)动态代理分为两大类,基于接口的动态代理和基于类的动态代理
3.1 基于接口:JDK动态代理【这里使用】
3.2 基于类:cglib
3.3 Java字节码实现:javasist

两个类:Proxy(代理),InvocationHandler(调用处理程序)

	public class ProxyInvocationHandler implements InvocationHandler {
    //被代理的接口
    private Object target;
    public void setTarget(Object target) {
        this.target = target;
    }
    //生成代理类
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);

    }
    //处理代理实例并返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //动态代理的本质就是使用反射机制实现
        Object result = method.invoke(target, args);
        return result;
    }
}
public class Client {
    public static void main(String[] args) {
        //真实角色
        Host host = new Host();
        //通过调用程序处理来处理要调用的接口对象
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        //设置要代理的对象
        pih.setTarget(host);
        //动态生成代理类
        Rent proxy = (Rent) pih.getProxy();
        proxy.rent();
    }
}

动态代理好处:
可以使真实角色操作更加纯粹,不用关注一下公共业务。
公共业务交给代理角色,实现业务分工。
公共业务发送扩展时候,方便集中管理。
一个动态代理类代理的是一个接口,一般就是对应的一类业务。
一个动态代理可以代理多个类,只要是实现了同一个接口即可。

使用spring实现AOP

方式一:使用Spring的API接口

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 query() {
        System.out.println("查询了一个人");
    }
}

加入的日志类

public class Log implements MethodBeforeAdvice {
    //method:要执行的目标对象的方法
    //args:参数
    //target:目标对象
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}
public class AfterLog implements AfterReturningAdvice {
    //returnValue:返回值
    //method:要执行的目标对象的方法
    //args:参数
    //target:目标对象
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"方法被执行了,返回结果为:"+returnValue);
    }
}
<!--注册bean-->
    <bean id="userService" class="com.study.service.UserServiceImpl"/>
    <bean id="log" class="com.study.log.Log"/>
    <bean id="afterLog" class="com.study.log.AfterLog"/>
    <!--方式一:使用原生的Spring API接口-->
    <!--配置AOP,需要导入aop的约束-->
    <aop:config>
        <!--切入点   expression:表达式   execution(要执行的位置 * * * * *)-->
        <aop:pointcut id="pointcut" expression="execution(* com.study.service.UserServiceImpl.*(..))"/>
        <!--执行环绕增加-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>

测试:注意动态代理代理的是接口

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

方式二:自定义实现AOP【定义切面】

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

切面配置

    <!--方式二:自定义类-->
    <bean id="diy" class="com.study.diy.DiyPointCut"/>
    <aop:config>
        <!--自定义切面,ref是要引用的类-->
        <aop:aspect ref="diy">
            <!--切入点-->
            <aop:pointcut id="point" expression="execution(* com.study.service.UserServiceImpl.*(..))"/>
            <!--通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

方式三:使用注解实现

//方式三:使用注解
@Aspect  //标注这个方法是一个切面
public class AnnotationPointCut {
    @Before("execution(* com.study.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("++++++++方法执行前");
    }
    @After("execution(* com.study.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("++++++++方法执行后");
    }
    //在环绕增强中,我们可以给定一个参数,代表要处理的切入点,类似动态代理的方法
    @Around("execution(* com.study.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        Signature signature = jp.getSignature();//获得签名
        System.out.println("signature"+signature);
        jp.proceed();//执行方法
        System.out.println("环绕后");
    }
}
    <!--方式三:注解-->
    <bean id="annotationPointCut" class="com.study.diy.AnnotationPointCut"/>
    <!--开启注解支持   默认用JDK方式实现(expose-proxy="false")  如果用cglib实现(expose-proxy="true")-->
    <aop:aspectj-autoproxy expose-proxy="true"/>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值