首页 > 编程语言 > 详细

Spring框架系列2--装配和注入Bean

时间:2019-06-04 16:01:42      阅读:207      评论:0      收藏:0      [点我收藏+]

  企业日常开发中,几乎都是Spring系的框架,无论是SSM、还是现在大火的SpringBoot+JPA/MyBatis,使用最大的目的就是简化开发

基本模块:

技术分享图片

核心容器:Beans、Core、Context、SpEL

1. core和beans模块提供了整个框架最基础的部分,包括了IoC(控制反转)和Dependency Injection(依赖注入)。

2. Context建立在Core和Beans模块提供的基础之上:他提供了框架式访问对象的方式

3. core、beans、context构成了Spring的骨架

4. SpEL:提供了一种强大的用于在运行时操作对象的表达式语言

优点:

  1、对象之间的依赖关系通过IOC容器进行管理,降低组件之间的耦合,不需要总是new一个对象

  2、提供面向切面编程

  3、功能丰富,Transaction、JDBC、WebSocket等

  4、轻量级:大小和开销方面都是轻量级的

  5、开放性很高,可以选择自己想要使用的功能

装配Bean

  pojo的使用体现了非侵入式编程,通过DI进行装配

装配方式:

  1、xml显式配置

  2、java中显式配置

  3、隐式的bean发现机制和自动装配

StudentDaoImpl.java

public class StudentDaoImpl implements StudentDao {
    @Override
    public void add() {
        System.out.println("add");
    }

    @Override
    public void del() {
        System.out.println("del");
    }
}

StudentServiceImpl.java

@Data
@AllArgsConstructor
public class StudentServiceImpl implements StudentService {

    private StudentRepository studentResponstory;

    @Override
    public void add() {
        System.out.println("add");
    }

    @Override
    public void del() {
        System.out.println("del");
    }
}

1、xml显式配置

Spring最开始的配置方式,相比注解装配和java配置比较麻烦

<?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 http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
    <beans>
        <bean id="studentDao" class="com.it.dao.impl.StudentDaoImpl"/>
        <bean id="studentService" class="com.it.service.impl.StudentServiceImpl" >
            <constructor-arg ref="studentDao" />
        </bean>
    </beans>

</beans>

xml文件中首先要声明多个xml模式文件,这些xsd文艺了配置spring xml元素

通过<bean>去配置,id如果省略的话,自动生成名称:"class内容"#0,客户性较差,一般主动声明,首字母要小写

2、java中显式配置

java显式配置主要适用于自动装配无法实现的情况(例如,使用第三方库中的组件,没办法使用@component被扫描到)。

WebConfig.java

@Configuration
@ComponentScan
public class WebConfig  extends WebMvcConfigurerAdapter {

    @Bean
    public Gson gson() {
        return new Gson();
    }
}

我们使用Gson、ModelMapper这种第三方组件一般都是通过这种方式进入装配

关键是@Configuration注解,表示WebConfig是一个配置类

除此之外,还有一个联合注解@Conditional(WebCondition.class),matches()方法返回true,就会创建Bean,返回false,不会创建

@Bean
@Conditional(WebCondition.class)
public Gson gson() {
    return new Gson();
}

WebCondition.java

public class WebCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        return false;
    }
}

3、自动化装配Bean

实现:

1、自动扫描@ComponentScan,自动发现应用上下文中所创建的 bean

2、自动装配@Autowired,自动满足 bean 之间的依赖

例如上面例子service和dao之间关系,dao上面都要通过@Component("StudentDao")声明是个组件,通过config的@ComponentScan去扫描(也可以

在xml配置扫描),通过@Autowired去自动注入

@Service
public class StudentServiceImpl implements StudentService {

    private StudentDao studentDao;

    @Override
    public void add() {
        studentDao.add();
    }

    @Override
    public void del() {
        studentDao.del();
    }
}

注入的方式一般有两种:

  1、@Autowired按类型注入,只能是当有且仅有一个匹配的Bean才可以,如果有多个,就需要和@Qualifier联合使用,确定唯一的实现类,相

比@Resource多一个required属性,如果等于false,即使没有发现这个bean,也不会抛出异常

  2、@Resource按名称注入,建议指明name值,@Resource(name="xxx"),这个注解是javax带有的,而不是Spring的注解

这三种方式可以搭配使用,原则是:尽可能地使用自动配置的机制,显式配置越少越好

Bean注入方式

1、属性注入

2、构造器注入

3、工厂方法注入

Student.java

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {

    private int id;
    private String name;
    private int age;
}

1、属性注入,也就是setter注入

需要生成属性的set方法

<?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 http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
    <beans>
        <bean id="student" class="com.it.entity.Student">
            <property name="id" value="1001" />
            <property name="name" value="sam" />
            <property name="age" value="25" />
        </bean>
        
    </beans>

</beans>

2、构造器注入

School.java

@Data
@AllArgsConstructor
public class School {
    private Student student;
}
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
    <beans>
        <bean id="student" class="com.it.entity.Student" />
        <bean id="school" class="com.it.entity.School" >
            <constructor-arg name="student" ref="student" />
        </bean>
    </beans>

</beans>

3、工厂方法注入:静态工厂和实例工厂

School.java

public class School {

    public Teacher createTeacher() {
        Teacher teacher = new Teacher();
        teacher.setId(1001);
        teacher.setName("sam");
        return teacher;
    }

    public static Teacher createTeacher1() {
        Teacher teacher = new Teacher();
        return teacher;
    }
}
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
    <beans>

        <bean id="school" class="com.it.entity.School" />
        <bean factory-bean="school" factory-method="createTeacher" />

        <bean id="school1" class="com.it.entity.School" factory-method="createTeacher1"/>
    </beans>

</beans>

Bean的作用域

在默认情况下, Spring 应用上下文中所有 bean 都是作为以单例( singleton )的形式创建的。也就是说,不管给定的一个 bean 被注入到其他

bean多少次,每次所注入的都是同一个实例

作用域:

  1、单例Singleton:在整个应用中,只创建 bean 的一个实例。

  2、原型Prototype:每次注入或者通过 Spring 应用上下文获取的时候,都会创建一个新的 bean 实例。

  3、会话Session:在 Web 应用中,为每个会话创建一个 bean 实例。

  4、请求Rquest:在 Web 应用中,为每个请求创建一个 bean 实例。

如果选择非单例,通过@Scope设置

例如Student需要设置为Prototype

@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class Student {


}

 

Spring框架系列2--装配和注入Bean

原文:https://www.cnblogs.com/huigelaile/p/10973913.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!