2013-03-20 62 views
1

我有类A,B及其实现AImpl,BImplSpring框架中的Java配置

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

要配置吉斯依赖我会写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(缺点) tructor和配置)。
  • 我应该写更多的代码(CIMP和的AIMP1需要创建方法,而不是一个表达式)

是否有什么办法impruve我的spring配置而不做XML?

upd 我不想用类似@Component的弹簧相关注释来监视我的类。而且我更喜欢构造函数注入任何其他注入。扫描也不是最好的解决方案。那么,我可以用Guice做Spring吗?

UPD2

所以我想归档

  • 自动装配
  • ,构造器注入

没有

  • XML
  • PathScan

回答

2

而不是使用Java代码,你可以使用自动装配Bean的创造。您可以在您的java配置中定义ComponentScan。您不需要使用任何XML文件。

+0

我可以做自动装配不scaning和xml春天? – 2013-03-20 10:06:09

+0

我还没有遇到任何这样的解决方案。自动装配是由Spring容器完成的,它基于你在ComponentScan中定义的包并且在初始化时完成一次。不知道你试图通过避免这个问题来解决什么问题。 – 2013-03-20 10:08:45

+0

在componentScan出现时,我似乎对我进行测试时感到很兴奋。除此之外,对我来说这似乎是一个不好的习惯。 – 2013-03-20 10:11:32

0

这将创建无豆xml和污染豆类OK使用Spring注解:

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); 
    } 
} 
+0

现在这是它的工作原理。但我如何将'B'自动装入'AImpl'? – 2013-03-20 10:25:50