1

我的 spring.xml 如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd

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

</beans>

我有 Test1 课

package com.mkyong.service;

import org.springframework.stereotype.Component;
@Component("test1")
public class Test1 {
public int i=1;
}

我有一个应用类

package com.mkyong.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mkyong.service.Test1;

public class App 
{
    @Autowired
    Test1 test1;

    public static void main( String[] args )
    {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "spring.xml");
        App app=new App();

        System.out.println(app.test1);
    }

}

但我得到的输出为空。我不能正确地自动装配它。我做错了什么?

4

2 回答 2

9

当你这样做时:

App app=new App();

它创建了一个不受 Spring 管理的 App 的新实例,因此您不会拥有自动装配的组件。

您需要在 spring xml 中声明 App bean,然后使用检索它context.getBean("beanName")

例如,在 Spring XML 中,您可以像这样声明 bean:

<bean id="app" class="com.mkyong.common.App" />

然后将其取回,context.getBean("app")然后它将具有 Autowired 组件。

于 2013-06-27T08:09:55.723 回答
6

You don't have to search for your bean using context.getBean("beanName"). This introduces
unnecessary dependency on Spring framework. That's not very clean.

It could be better to annotate your App class with @Configurable annotation.

...
@Configurable
public class App 
{
    @Autowired
    Test1 test1;
...

and add to your spring.xml one tag:

<context:spring-configured />

Thats all. Now you can create your App class as you wanted and autowiring will work.

...
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
App app=new App();
System.out.println(app.test1);
...

Note: you need spring-aspects, spring-aop, aspectjrt on your classpath.

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aop</artifactId>
</dependency>
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjrt</artifactId>
</dependency>
于 2013-06-27T09:00:49.407 回答