2013-08-01 69 views
2

我一直在尝试使用自动装配,但未能获得自动装配。这里是代码片段,自动装配未在春季发生

应用程序上下文文件:

<context:annotation-config /> 
    <context:component-scan base-package="com.shapes" /> 

    <bean id = "triangle" class = "com.shapes.Triangle" autowire="byName"></bean> 

三角类:

@Component 
public class Triangle implements Shape { 

    @Override 
    public void draw() { 
     System.out.println("In draw"); 

    } 

} 

主要类:

public class MainShapes { 

    @Autowired 
    private Triangle triangle; 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     MainShapes shapes = new MainShapes(); 
     shapes.triangle.draw(); 

    } 
} 
+0

它启动你的自动装配Autowired豆你在哪里,你启动应用程序''上下文文件?你必须首先加载'context'来使用'ClassPathxmlApplicationcontext()'初始化bean' – SRy

+0

检查这个例子:http://www.mkyong.com/spring3/spring-3-hello-world-example/ – SRy

回答

2

只有春季管理的bean将得到自动自动装配(除非你使用某种AOP)。

在主类中手动创建MainShapes,并没有什么不同之处注释春天有关。

它不会神奇地以这种方式工作。你可能想找回您的MainShapes从Spring IoC容器(并确保它是在应用程序上下文中)...

相关问题