spring @autowired - 不使用硬编码的xml文件

时间:2013-06-08 04:57:05

标签: spring autowired

我正在尝试使用struts2和spring实现一个示例项目。我跟着this示例,它运行正常。但是在每个动作中我都需要硬编码spring.xml配置文件,如下所示。我怎样才能摆脱以下陈述?

ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {“SpringBeans.xml”});

Customer cust = (Customer)context.getBean(“CustomerBean”);
System.out.println(cust);

我想写下面的内容

@Autowired
Customer customer;

上述声明是否有效?如果是,spring将如何查找xml配置文件?会在classpath中检查一下吗?

1 个答案:

答案 0 :(得分:1)

正如@ engineer-dollery所说,Spring ApplicationContext应该只有一个引导程序。您可以自己实例化它(如在您的示例中),但对于基于servlet的Web应用程序执行此操作的典型方法是在web.xml中添加以下内容:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:SpringBeans.xml</param-value>
</context-param>

然后,如果您想使用自动装配,可以在SpringBeans.xml文件中定义以下内容:

...
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
...
<context:component-scan base-package="package.containing.your.beans" />

并确保使用@Autowired@Component(或@Service使用Spring MVC而不是Struts来注释具有@Controller字段且具有适当构造型的类

但请注意,依赖关系只能通过自动装配注入,如果它们本身是:

  1. 在xml配置中定义为bean或
  2. 使用构造型注释,并在一个包中告诉Spring扫描组件
  3. 否则,请看一下这些有关Spring和Struts集成的教程/示例: