【问题标题】:Proxied FactoryBean implementation in Spring bootSpring Boot 中的代理 FactoryBean 实现
【发布时间】:2020-07-06 12:03:32
【问题描述】:

我想实现FactoryBean 接口来初始化我的bean。但我想将代理对象注入到我的服务中。

@Configuration
public class SomeContextFactory implements FactoryBean<SomeClass>
{
  //implementation
}

我应该如何为代理对象更改此代码? (春季启动,无 xml)

我需要通过getObject()动态生成对象并将这些对象注入到一些单例服务中。

附加:使用我的自定义范围(或原型范围)

【问题讨论】:

  • 您能澄清一下您的问题吗?添加更多细节。 (即代理对象、服务等..)

标签: java spring-boot scope


【解决方案1】:

假设你有SomeClassSomeContextFactory

public class SomeClass {

    private int id;

// Setter
// Getter
// All args contructor
}


public class SomeContextFactory implements FactoryBean<SomeClass>
{
    private int someClassId;
 
    @Override
    public SomeClass getObject() throws Exception {
        return new SomeClass(someClassId);
    }
 
    @Override
    public Class<?> getObjectType() {
        return SomeClass.class;
    }
 
    @Override
    public boolean isSingleton() {
        return true; // for singleton scope
    }

  //  @Override
  //  public boolean isPrototype() {
  //     return true; // for prototype scope
  // }


// Setter
// Getter

}

现在,你必须告诉spring-boot FactoryBean

@Configuration
public class FactoryBeanAppConfig {
  
    @Bean
    public SomeContextFactory someContextFactory() {
        SomeContextFactory factory = new SomeContextFactory();
        factory.someClassId(5);
        return factory;
    }
 
    @Bean
    public SomeClass someClass() throws Exception {
        return someContextFactory().getObject();
    }
}

最后,您的 Bean SomeClass 已准备好注入:

@Service
public class SomeService implements ISomeService{

@Autowired 
private SomeClass someClass;

public void useSomeClassAndPerformAction(){
 // implementation...
 }
}

【讨论】:

  • 可以用原型作用域做到这一点吗?
  • 是:用 isProtoype() 替换 isSingleton() 返回 true @Override public boolean isPrototype() { return true; // 原型作用域 }
  • 但是 SomeClass 没有被代理
  • 你能解释一下你所说的代理是什么意思吗?你到底需要什么?
猜你喜欢
  • 2017-06-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-25
  • 1970-01-01
相关资源
最近更新 更多