java - 如何创建一个 bean 作为接口(interface)类的实例

标签 java spring

我有三个类1)一个接口(interface)2)一个实现接口(interface)的类3)一个静态工厂,它返回一个实例第二类作为实例接口(interface)类

public Interface MyInterface {
}

public class Myclass implements MyInterface {
}

public Class MyStaticFactory {

    public static MyInterface getInstance() {
        MyInterface myClassInstance = new Myclass();
        return myClassInstance;
     }
}

我想创建一个 MyClass 的 bean 作为 MyInterface 的实例。我的代码是

<bean id="staticFactory" class="MyStaticFactory"> 
</bean>

<bean id="myclass" class="MyInterface" factory-bean="staticFactory" factory-method="getInstance"> 
</bean>

但是使用上面的代码我遇到了异常

org.springframework.beans.factory.BeanCreationException: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private MyInterface ; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [MyInterface] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at com.amazon.coral.reflect.instantiate.SpringInstantiatorFactory$1.newInstance(SpringInstantiatorFactory.java:175)

我正在尝试使用以下代码访问 bean

@Autowired
private MyInterface MyclassInstance

创建一个 bean 作为 InterfaceClass 的实例是否有效?我们如何使用 spring 将 MyClass 的实例加载到 MyInterface 的类变量中?

最佳答案

您不需要 Autowiring 任何字段,因为您有自己的工厂可以为您实例化 bean。另外,您不需要使用其中的静态方法实例化工厂类。相反,您可以继续:

<bean id="staticFactory" class="MyStaticFactory" factory-method="getInstance" />

现在假设您有 MyInterface 的多个实现,您可以通过传递如下参数来实现:

<bean id="staticFactory" class="MyStaticFactory" factory-method="getInstance" scope="prototype">
    <constructor-arg value="MyClass" />
</bean>

在工厂类中,您可以使用 switch(来自 JDK 7)或 if elseladder 来检查方法 getInstance 方法的参数中请求的内容并实例化正确的 bean。

然后您可以执行以下操作:

public static void main(String args[]) {
    Application context = new ......
    MyInterface myIface = context.getBean("staticFactory", MyInterface.class);
    //myIface.mymethod();
}

关于java - 如何创建一个 bean 作为接口(interface)类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27587392/

相关文章:

java - 无法解析 Hibernate validator 消息

java - 为什么 Spring Boot 强制我使用 Thymeleaf 模板

java - maven模块,将persistence.xml与Spring连接

java - final方法模拟

java - Osmosis WayNode 实例始终从 getLatitude 和 getLongitude 返回 0

java - Java中的树结构?

java - 使用反射制作对象

java - jQuery AJAX 调用 Spring Controller 时出现 404 not found 错误

java - Spring 安全 : using relative path

java - 使用 spring boot 设置 Redis sentinel