首页 > 其他分享 >Spring

Spring

时间:2022-11-20 18:23:43浏览次数:32  
标签:装配 Autowired Spring bean 注解 public

对象是由Spring创建的

对象属性是由Spring容器设置的

控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的

反转:程序本身不创建对象,而编程被动的接收对象

依赖注入:就是利用set方法来进行注入的

IOC是一种编程思想,由主动的编程变成被动的接收

可以通过new ClassPathXmlApplicationContext 去浏览底层源码

//常用依赖
  <!--springMVC坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

注解说明

  • @Autowired:自动装配通过类型。名字
    如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value="xxx")
  • @Nullable :字段标记了这个注解,说明这个字段可以为null
  • @Resource : 自动装配通过名字
  • @Component: 组件, 放在类上, 说明这个类被Spring管理了,就是bean!

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

    <bean id="..." class="...">  
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>


该id属性是标识单个bean定义的字符串

该class属性定义bean的类型并使用完成限定的类名

1.2、IOC创建对象的方式

1.使用无参构造创建对象,默认

2.有参构造创建对象

<!--第一种,下标赋值-->
    <bean id='user' class='com.aaa.dao.UserDaoImpl'>
    <constructor-arg index='0' value='zcf'/>
    </bean>
<!--第二种方式:通过类型创建,不建议使用-->
<bean id='user' class='com.aaa.pojo.User'>
	<constructor type='java.lang.string' value='zcf'/>
</bean>
<!--第三种,直接通过参数名来设置-->
<bean id='user' class='com.kuang.pojo.User'>
 	<constructor-arg name='name' value='zcf'
</bean>

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

1.3、Spring配置

1.3.1、别名

<!--别名, 如果添加了别名,我们可以使用别名获取这个对象,name也是设置别名的-->
<alias name="user" alias="user1"/>

1.3.2、Bean的配置

<!--
	id: bean 的唯一标识符,也就是相当于我们学的对象名
	class:bean 对象所对应的全限定名:包名+类名
	name:也是别名,而且name 可以同时取多个别名
-->
< bean id ="user" class="包名 + 类名" name="user1, user2 u3;u5"/>

1.3.3、import

这个import, 一般用于团队开发使用,他可以将多个配置文件合并到一个

<import resource="beans.xml"/>

2、依赖注入

2.1、构造器注入

2.2、set注入

<bean id="user" class="com.aaa.pojo.User">
        <property name="username" value="zcf"></property>
    </bean>
    <bean id="address" class="com.aaa.pojo.Address">
        <property name="name" value="zz"/>
        <property name="user" ref="user"></property>
        <!--数组注入-->
        <property name="books">
            <array>
                <value>1</value>
                <value>2</value>
            </array>
        </property>
        <!--list集合注入-->
        <property name="hobbys">
            <list>
                <value>zzzz</value>

            </list>
        </property>
        <!--map集合注入-->
        <property name="card">
            <map>
                <entry key="1" value="zcf"/>
            </map>
        </property>
        <!--set集合注入-->
        <property name="games">
            <set>
                <value>zcvzx</value>
                <value>afafaw</value>
            </set>
        </property>
    </bean>


还有一个p命名空间和c命名空间注入

<!--需要导入约束-->
mlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
<!--p命名空间-->
  <bean id="user" class="com.aaa.pojo.User" p:username="zzzzzzzzz">
<!--c命名空间-->
 <bean id="user" class="com.aaa.pojo.User">
 <constructor-arg name="thingTwo" value="zzzzzzzzzzzz"/>  
 </bean>

3、bean作用域

1、单例模式(Spring默认机制)

<bean id="user" class="com.aaa.pojo.User" scope="singleton">
        <property name="username" value="zcf"></property>
    </bean>

2、原型模式:每次从容器中get的时候,都会产生一个新的对象

<bean id="user" class="com.aaa.pojo.User" scope="prototype">
        <property name="username" value="zcf"></property>
    </bean>

3、其余的request、session、application、这些只能在web开发中使用到

4、bean自动装配

<!--byName: 会自动再容器上下文中查找,和自己对象set方法后面的值对应的beanid-->
<bean id="user" class="com.aaa.pojo.User" autowire="byName">
        <property name="username" value="zcf"></property>
    </bean>
<!--byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean-->
<bean id="user" class="com.aaa.pojo.User" autowire="byType">
        <property name="username" value="zcf"></property>
    </bean>

小结:

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

5、 使用注解实现自动装配

要使用注解须知:

  • 1、导入约束:context约束

  • 2、配置注解的支持

    <?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)容器中存在

    如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解@Autowired完成的时候,我们可以使用@Qualifier(value="xxx")去配置@Autowired的使用,指定一份唯一的bean对象注入

    小结:

    @Resource和@Autowired区别:

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

8、使用注解开发

<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.aaa.pojo"/>

2、属性注入

@Component
public class User{
    @value("zcf")  在这也可以注入
    private String name;
    
    //相当于<property name="name" value="zcf"/>
    @Value("zcf")
    public void setName(String name){
        this.name=name
    }
}
    

3、衍生的注解

@Component有介个衍生注解,我们在web开发中,会按照MVC三层架构分层

  • dao 【@Repository】
  • service 【@Service】
  • controller 【@Controller】

这是个注解功能都是一样的,都是代表将某个类注册到Spring中,装配到Bean

4、自动装配

  • @Autowired:自动装配通过类型。名字
    如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value="xxx")
  • @Nullable :字段标记了这个注解,说明这个字段可以为null
  • @Resource : 自动装配通过名字

5、作用域

  • @Scope("")

6、小结

​ xml与注解:

  • xml更加万能,适用于任何场合!维护 简单方便

  • 注解不是自己类使用不了,维护相对复杂

  • xml用来管理bean

  • 注解只负责完成属性的注入

  • 我们在使用的过程中需要注意一个问题:必须让注解生效,就需要开启注解的支持

    <!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.aaa.pojo"/>
    <!--开启注解支持-->
    <context:annotation-config/>
    
    

9、使用java的方式配置Spring

我们现在要完全不使用Spring的xml配置,全权交给java来做!

JavaConfig是spring的一个子项目,在spring 4之后,它成为了一个核心功能

//这个也会被spring容器托管,注册到容器中,因为他本来就是一个@Component
//@Configuration 代表这是一个配置类,相当于一个xml文件
@ComponentScan("com.aaa.pojo") //扫描包
public class Config{
    //注册一个bean, 就相当于写一个bean标签
    // 这个方法的名字,就相当于bean标签中的id属性
    // 这个方法的返回值,就相当于bean标签中的class属性
    @Bean
    public User user(){
        return new User();//就是返回要注入到bean的对象
    }
}

10、代理模式

  • 动态代理和静态代理角色一样
  • 动态代理的代理类是动态生成的,不是我们直接写好的
  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
    • 基于接口--- JDK 动态代理
    • 基于类cglib
//等我们会用这个类,自动生成代理类
public class ProxyHandler  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);
    }

    //处理代理实例,并返回结果
    @Override
    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) {
        //真实的角色
        User user = new User();
        //代理角色:现在没有
        ProxyHandler proxyHandler = new ProxyHandler();
       //通过调用程序处理角色来处理我们要调用的接口对象
        proxyHandler.setTarget(user);
        Rent proxy = (Rent) proxyHandler.getProxy();  //这个类就是动态生成的代理类proxy
        proxy.Rent();
    }
}

11、使用Spring实现Aop

使用AOP,需要导入一个依赖包

 <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>

使用Spring的API接口

    <!--配置aop: 需要导入aop的约束-->
        <aop:config>
            <!--切入点:expression: 表达式, execution(要执行的位置)-->
            <aop:pointcut id="pointcut" expression="execution()"/>
            <aop:advisor advice-ref="要切入执行的方法" pointcut-ref="pointcut"/>
        </aop:config>

标签:装配,Autowired,Spring,bean,注解,public
From: https://www.cnblogs.com/zcf94264/p/16909125.html

相关文章