Spring Register Bean Series - Method 6: Implement the FactoryBean interface

Original website: Spring Register Bean Series--Method 6: Implement FactoryBean Interface

Introduction

        This article introduces Spring's method of registering beans: implementing the FactoryBean interface.

         I wrote a series of methods for registering beans, see: Spring Registering Beans (Providing Beans) Series--Method Encyclopedia

Method overview

  1. Implement the FactoryBean interface
  2. Inject the implementation class of step 1 into the container

example

Implementation class of FactoryBean interface

package com.knife.factoryBean;

import com.knife.entity.MyBean;
import org.springframework.beans.factory.FactoryBean;

public class MyFactoryBean implements FactoryBean<MyBean> {
    @Override
    public MyBean getObject() throws Exception {
        // 这里可以进行一些其他操作,比如填充属性等
        return new MyBean();
    }

    @Override
    public Class<?> getObjectType() {
        return MyBean.class;
    }

    //是否单例(默认为true)
    //true:这个bean是单例,在容器中只保存一份
    //false:多实例,每次获取都会创建一个新的bean;
    @Override
    public boolean isSingleton() {
        return true;
    }
}

The class to be registered (Bean)

package com.knife.entity;

public class MyBean {
    public String sayHello() {
        return "Hello World";
    }
}

Configuration class (register the implementation class of the FactoryBean interface)

package com.knife.config;

import com.knife.factoryBean.MyFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfiguration {
    @Bean
    public MyFactoryBean myFactoryBean() {
        return new MyFactoryBean();
    }
}

test

package com.knife.controller;

import com.knife.entity.MyBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @Autowired
    private MyBean myBean;

    @GetMapping("/test")
    public String test() {
        return myBean.sayHello();
    }
}

result

Guess you like

Origin blog.csdn.net/feiying0canglang/article/details/126897737