Spring系列文章:Bean的获取⽅式

简介: Spring系列文章:Bean的获取⽅式

一、简介

Spring为Bean提供了多种实例化⽅式,通常包括4种⽅式。(也就是说在Spring中为Bean对象的创建准 备了多种⽅案,⽬的是:更加灵活)

第⼀种:通过构造⽅法实例化

第⼆种:通过简单⼯⼚模式实例化

第三种:通过factory-bean实例化

第四种:通过FactoryBean接⼝实例化

二、四种Bean的获取⽅式

1、通过构造⽅法获取(实例化)

默认情况下,会调⽤Bean的⽆参数构造⽅法

spring.xml中配置bean的路径

<?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="userBean" class="com.demo.bean.User"/>
 
</beans>
 
public class User {
    public User(){
        System.out.println("无参构造被调用");
    }
}

 

测试

    @Test
    public void testConstructor() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        User user = applicationContext.getBean("userBean", User.class);
        System.out.println(user);
    }

2、通过简单⼯⼚模式获取(实例化)

第一步:定义⼀个Bean

public class User {
   
}

第二步:编写简单⼯⼚模式当中的⼯⼚类

public class UserFactory {
    public static User get(){
        return new User();
    }
}

第三步:在Spring配置⽂件中指定创建该Bean的⽅法(使⽤factory-method属性指定)

1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans xmlns="http://www.springframework.org/schema/beans"
3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4.        xsi:schemaLocation="http://www.springframework.org/schema/beans
5. http://www.springframework.org/schema/beans/spring-beans.xsd">
6. 
7.     <!--factory-method指定的是工厂类中的静态方法,也就是告诉spring框架 调用这个方法可以获取bean-->
8.     <bean id="userBean" class="com.demo.entity.UserFactory" factory-method="get"/>
9. 
10. </beans>

第四步:编写测试程序

    @Test
    public void testSimpleFactory(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        User user = applicationContext.getBean("userBean", User.class);
        System.out.println(user);
    }

3、通过factory-bean获取(实例化)

这种⽅式本质上是:通过⼯⼚⽅法模式进⾏实例化。

第⼀步:定义⼀个Bean

public class Order{
   
}

第⼆步:定义具体⼯⼚类,⼯⼚类中定义实例⽅法

public class OrderFactory {
     public Order get(){
         return new Order();
     }
}

第三步:在Spring配置⽂件中指定factory-bean以及factory-method

<bean id="orderFactory" class="com.demo.bean.OrderFactory"/>
<bean id="orderBean" factory-bean="orderFactory" factory-method="get"/>

第四步:编写测试程序

    @Test
    public void testSimpleFactory(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        Order orderBean = applicationContext.getBean("orderBean", Order.class);
        System.out.println(orderBean);
    }

4、通过FactoryBean接⼝实例化

以上的第三种⽅式中,factory-bean是我们⾃定义的,factory-method也是我们⾃⼰定义的。

在Spring中,当你编写的类直接实现FactoryBean接⼝之后,factory-bean不需要指定了,factory-method也不需要指定了。

factory-bean会⾃动指向实现FactoryBean接⼝的类,factory-method会⾃动指向getObject()⽅法。

第⼀步:定义⼀个Bean

public class Person {
}

第⼆步:编写⼀个类实现FactoryBean接⼝

//PersonFactoryBean 也是一个bean 只不过这个bean比较特殊,叫做工厂bean,通过工厂bean这个特殊的bean可以获取一个普通的bean
public class PersonFactoryBean implements FactoryBean<Person> {
    @Override
    public Person getObject() throws Exception {
//最终这个bean还是程序员自己new
        return new Person();
    }
 
    @Override
    public Class<?> getObjectType() {
        return null;
    }
 
//这个方法在接口中有默认的实现,默认返回true 表示单例的,若多例直接将这个方法修改reture false即可
 
    @Override
    public boolean isSingleton() {
        // true表示单例
        // false表示原型
        return true;
    }
}

第三步:在Spring配置⽂件中配置FactoryBean

<bean id="personBean" class="com.demo.bean.PersonFactoryBean"/>

第四步:测试

    @Test
    public void testSimpleFactory(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        Person personBean = applicationContext.getBean("personBean", Person.class);
        System.out.println(personBean);
        Person personBean2 = applicationContext.getBean("personBean", Person.class);
        System.out.println(personBean2);
    }

FactoryBean在Spring中是⼀个接⼝。被称为“⼯⼚Bean”。“⼯⼚Bean”是⼀种特殊的Bean。所有 的“⼯⼚Bean”都是⽤来协助Spring框架来创建其他Bean对象的。

三、BeanFactory和FactoryBean的区别

Spring IoC容器的顶级对象,BeanFactory被翻译为“Bean⼯⼚”,在Spring的IoC容器中,“Bean⼯ ⼚”负责创建Bean对象。

这是 IOC 容器的基本实现,是 Spring 内部使用的接口。面向 Spring 本身,不提供给开发人员使用

FactoryBean:它是⼀个Bean,是⼀个能够辅助Spring实例化其它Bean对象的⼀个Bean。

在Spring中,Bean可以分为两类:

第⼀类:普通Bean

第⼆类:⼯⼚Bean(记住:⼯⼚Bean也是⼀种Bean,只不过这种Bean⽐较特殊,它可以辅助 Spring实例化其它Bean对象。)

四、注⼊⾃定义Date

前面文章有介绍到java.util.Date在Spring中被当做简单类型,简单类型在注⼊的时候可以直接使⽤value属 性或value标签来完成。但我们之前已经测试过了,对于Date类型来说,采⽤value属性或value标签赋值 的时候,对⽇期字符串的格式要求⾮常严格,必须是这种格式的:Mon Oct 10 14:30:26 CST 2022。其 他格式是不会被识别的。如以下代码:

public class Student {
    private Date birth;
 
    public void setBirth(Date birth) {
        this.birth = birth;
    }
 
    @Override
    public String toString() {
        return "Student{" +
                "birth=" + birth +
                '}';
    }
}
<bean id="studentBean" class="com.demo.bean.Student">
 <property name="birth" value="Mon Oct 10 14:30:26 CST 2002"/>
</bean>
    @Test
    public void testDate(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        Student studentBean = applicationContext.getBean("studentBean", Student.class);
        System.out.println(studentBean);
    }

结果

如果把⽇期格式修改⼀下:

<bean id="studentBean" class="com.demo.bean.Student">
 <property name="birth" value="2002-10-10"/>
</bean>

执行就报错

这种情况下,我们就可以使⽤FactoryBean来完成这个操作。 编写DateFactoryBean实现FactoryBean接⼝:

public class DateFactoryBean implements FactoryBean<Date> {
    // 定义属性接收⽇期字符串
    private String date;
 
    // 通过构造⽅法给⽇期字符串属性赋值
    public DateFactoryBean(String date) {
        this.date = date;
    }
 
    @Override
    public Date getObject() throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.parse(this.date);
    }
 
    @Override
    public Class<?> getObjectType() {
        return null;
    }
}

编写spring配置⽂件:

<bean id="dateBean" class="com.demo.bean.DateFactoryBean">
 <constructor-arg name="date" value="1999-10-11"/>
</bean>
<bean id="studentBean" class="com.demo.bean.Student">
 <property name="birth" ref="dateBean"/>
</bean>


相关文章
|
XML Java 测试技术
Spring IOC—基于注解配置和管理Bean 万字详解(通俗易懂)
Spring 第三节 IOC——基于注解配置和管理Bean 万字详解!
935 26
|
存储 Java Spring
【Spring】获取Bean对象需要哪些注解
@Conntroller,@Service,@Repository,@Component,@Configuration,关于Bean对象的五个常用注解
421 12
|
存储 Java 应用服务中间件
【Spring】IoC和DI,控制反转,Bean对象的获取方式
IoC,DI,控制反转容器,Bean的基本常识,类注解@Controller,获取Bean对象的常用三种方式
557 12
|
缓存 Java Spring
实战指南:四种调整 Spring Bean 初始化顺序的方案
本文探讨了如何调整 Spring Boot 中 Bean 的初始化顺序,以满足业务需求。文章通过四种方案进行了详细分析: 1. **方案一 (@Order)**:通过 `@Order` 注解设置 Bean 的初始化顺序,但发现 `@PostConstruct` 会影响顺序。 2. **方案二 (SmartInitializingSingleton)**:在所有单例 Bean 初始化后执行额外的初始化工作,但无法精确控制特定 Bean 的顺序。 3. **方案三 (@DependsOn)**:通过 `@DependsOn` 注解指定 Bean 之间的依赖关系,成功实现顺序控制,但耦合性较高。
1130 4
实战指南:四种调整 Spring Bean 初始化顺序的方案
|
XML Java 数据格式
Spring容器Bean之XML配置方式
通过对以上内容的掌握,开发人员可以灵活地使用Spring的XML配置方式来管理应用程序的Bean,提高代码的模块化和可维护性。
490 6
|
XML Java 数据格式
Spring从入门到入土(bean的一些子标签及注解的使用)
本文详细介绍了Spring框架中Bean的创建和使用,包括使用XML配置文件中的标签和注解来创建和管理Bean,以及如何通过构造器、Setter方法和属性注入来配置Bean。
285 9
Spring从入门到入土(bean的一些子标签及注解的使用)
|
XML Java 数据格式
🌱 深入Spring的心脏:Bean配置的艺术与实践 🌟
本文深入探讨了Spring框架中Bean配置的奥秘,从基本概念到XML配置文件的使用,再到静态工厂方式实例化Bean的详细步骤,通过实际代码示例帮助读者更好地理解和应用Spring的Bean配置。希望对你的Spring开发之旅有所助益。
|
安全 Java 开发者
Spring容器中的bean是线程安全的吗?
Spring容器中的bean默认为单例模式,多线程环境下若操作共享成员变量,易引发线程安全问题。Spring未对单例bean做线程安全处理,需开发者自行解决。通常,Spring bean(如Controller、Service、Dao)无状态变化,故多为线程安全。若涉及线程安全问题,可通过编码或设置bean作用域为prototype解决。
381 1
|
Java 测试技术 Windows
咦!Spring容器里为什么没有我需要的Bean?
【10月更文挑战第11天】项目经理给小菜分配了一个紧急需求,小菜迅速搭建了一个SpringBoot项目并完成了开发。然而,启动测试时发现接口404,原因是控制器包不在默认扫描路径下。通过配置`@ComponentScan`的`basePackages`字段,解决了问题。总结:`@SpringBootApplication`默认只扫描当前包下的组件,需要扫描其他包时需配置`@ComponentScan`。