【问题标题】:Java configuration in Spring frameworkSpring框架中的Java配置
【发布时间】:2013-03-20 09:56:29
【问题描述】:

我有课程AB 及其实现AImplBImpl

interface A {
}
interface B {
}
interface C {
}
class AImpl{
    @Inject
    AImpl(B b){}
}
class BImpl{
    @Inject
    BImpl(String foo, C c){}
}
class CImpl{
}

要在 Guice 中配置依赖项,我会写 smt 之类的

bind(A.class).to(AImpl);
bind(C.class).to(CImpl);
@Provides B provideB(C c){
   return new BImpl("foo", c)
}

在春天我可以做 smt 喜欢

@Bean public A a() {
    return new AImpl(b())
}
@Bean public B b() {
    return new BImpl("foo", c());
}
@Bean public C c() {
    return new CImpl();
}

有几个缺点

  • 我应该写下 AImpl 在 2 个地方(构造函数和配置)需要 B。
  • 我应该编写更多代码(CImp 和 AImpl 需要创建方法而不是一个表达式)

有什么方法可以在不做 xml 的情况下改进我的 spring 配置?

更新 我也不想用 @Component 之类的与 spring 相关的注释来污染我的类。我更喜欢构造函数注入而不是任何其他类型的注入。扫描也不是优选的解决方案。 那么,我可以用 Guice 的方式做 Spring 吗?

upd2

所以我想要存档

  • 自动装配
  • 构造函数注入

没有

  • XML
  • 路径扫描

【问题讨论】:

    标签: java spring configuration guice constructor-injection


    【解决方案1】:

    您可以使用自动装配来代替使用 java 代码创建 Bean。您可以在您的 java 配置中定义 ComponentScan。您不需要使用任何 XML 文件。

    【讨论】:

    • 我可以在 Spring 中不扫描和 xml 进行自动装配吗?
    • 我还没有遇到过这样的解决方案。自动装配由 Spring 容器根据您在 ComponentScan 中定义的包完成,并在初始化时完成一次。不知道你想通过避免这个来解决什么问题。
    • 出现 componentScan 时对我进行测试似乎很有挑战性。除此之外,这对我来说似乎是一种不好的做法。
    • Spring 提供了优秀的测试框架。我从来没有遇到过任何问题。如果您可以突出显示确切的问题,那么我可以尝试提供帮助。我发现 ComponentScan 非常有帮助,否则每次您需要编写或修改代码以创建新 bean 和管理依赖项时。它也很灵活。
    【解决方案2】:

    这可以创建没有 xml 的 bean 并使用 Spring 注释污染 bean:

    interface A {
    }
    
    interface B {
    }
    
    interface C {
    }
    
    class AImpl implements A {
        AImpl(B b) {
        }
    }
    
    class BImpl implements B {
        BImpl(String foo, C c) {
        }
    }
    
    class CImpl implements C {
    }
    
    @Configuration
    class Config {
        @Bean public A a() {
            return new AImpl(b());
        }
    
        @Bean public B b() {
            return new BImpl("foo", c());
        }
    
        @Bean public C c() {
            return new CImpl();
        }
    }
    
    public class T1 {
    
        public static void main(String[] args) throws Exception {
            AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
        }
    }
    

    【讨论】:

    • 这就是它现在的工作方式。但是我如何将B 自动连接到AImpl
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 2021-02-19
    相关资源
    最近更新 更多