【Spring框架】Bean的实例化方式


Bean的实例化方式

Spring容器装配Bean的方式主要是两种:

  • 基于XML配置方式
  • 基于注解的形式

1、基于XML配置方式装配Bean

Bean基于配置方式实例化有三种形式:

  • 基于无参构造函数实例化bean
  • 基于静态工厂方式实例化bean
  • 基于普通工厂方式实例化bean

(1)基于无参构造函数实例化Bean

<!--基于无参构造实例化bean-->
    <bean id="person"  class="com.tulun.bean.Person1"/>

无参构造方式实例化Bean的xml配置信息如上,需要确保存在无参构造函数

(2)静态工厂方式实例化Bean

给定一个静态工厂类来获取Person对象

public class StaticFactory {
    
    
    public static Person1 getPerson() {
    
    
        return new Person1();
    }
}

交给IOC容器的配置如下:

 <!--基于静态工厂方式实例化bean-->
    <bean id="person1" class="com.tulun.factory.StaticFactory" factory-method="getPerson"/>

class属性指定的静态工厂类的全路径 ,factory-method属性即对应的方法,当前获取Person类在静态工厂下提供的getPerson方法可获取该对象

(3)基于普通工厂方法实例化Bean

基础工厂类定义如下:

public class CommonFactory {
    
    
    public Person1 getPerson() {
    
    
        return new Person1();
    }
}

配置Bean信息如下:

    <!--基于普通工厂方法实例化Bean-->
    <bean id="factoty" class="com.tulun.factory.CommonFactory"/>
    <bean id="person2" factory-bean="factoty" factory-method="getPerson"/>

2、基于注解的方式装配Bean

相比于XML形式装配bean会更加简单

(1)Spring配置文件引入context约束

<?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-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">


    <!--开启注解扫描:在指定的包路径下所有的类名,属性等上的注解都会进行扫描-->
    <context:component-scan base-package="com.tulun"/>
    
    <!--开启注解扫描:扫描属性上的注解:不推荐使用-->
    <!--<context:annotation-config></context:annotation-config>-->
</beans>

注意:使用标签一定要引入context约束,该约束下才提供了标签

(2)在交给IOC容器管理的类上添加注解

@Component
public class Person1 {
    
    
    private String name;
    private int id;
}

(3)通过IOC容器获取Person对象

 //获取IOC容器
 ApplicationContext context = new ClassPathXmlApplicationContext("application2.xml");
 //在容器中获取需要的对象
 Person1 person = (Person1) context.getBean("person1");
 System.out.println(person);

通过以上代码演示:使用注解很方便,在配置文件中指定扫描的包路径或者类路径后,另交给IOC管理的类上直接添加注解@Component

Spring中提供的4中注解来标注bean

  • @Component 通用的标注的注解
  • @Repository 对dao层实现类进行标注
  • @Service 对service层实现类进行标注
  • @Controller 对Controller层实现类进行标注

后端的业务分层一般业务请求顺序:Controller(进行URL结束和返回)→ Service(业务逻辑)→ Dao(访问数据层)

@Component 是Spring提供的通用的组件注解

@Repository@Service@Controller都是有其衍生出来,功能都是一样的,可以互换,主要是为了区分被注解的类处在不同的业务层,使逻辑更加清晰。

猜你喜欢

转载自blog.csdn.net/Super_Powerbank/article/details/113152698