我正在这个Spring MVC项目上工作,在这里我无法通过Dao实现的Interface在控制器中自动连接此Dao类。这是我的spring-config.xml的一部分。我正在使用aspectJAnnotationTX management

<aop:aspectj-autoproxy />
<context:component-scan base-package="com.simulator" />
<context:annotation-config />
<tx:annotation-driven />

<context:property-placeholder
        location="classpath*:config.properties" />

<bean id="oidDao" class="com.simulator.service.OidDao">
        <property name="ipaddressNC" value="${ipaddressNC}" />
        <property name="ipaddressOM" value="${ipaddressOM}" />
        </bean>


道课:

@Component

public class OidDao implements OidManager {

    @Autowired
    private SessionFactory sessionFactory;
    private String ipaddressNC;
    private String ipaddressOM;

    public  String getIpaddressNC() {
        return this.ipaddressNC;
    }

    public  void setIpaddressNC(String ipaddressNC) {
        this.ipaddressNC = ipaddressNC;
    }

    public  String getIpaddressOM() {
        return ipaddressOM;
    }

    public  void setIpaddressOM(String ipaddressOM) {
        this.ipaddressOM = ipaddressOM;
    }


OidManager:

public interface OidManager {

    public  String getIpaddressNC();
    public  String getIpaddressOM();
}


控制器:

@Controller
public class HomeController {
    @Autowired
    OidManager oim;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String indexpage(ModelMap modelMap) {

        ApplicationContext context =
                 new ClassPathXmlApplicationContext(new String[] {"spring-config.xml"});
         o = (OidManager)context.getBean("oidDao");

       o.getIpaddressNC(); // ---> this returns data read from ext properties file and works fine


                oim.getIpaddressNC(); // ---> this returns null`


我正在尝试重用Dao,因此我不想从每个方法多次调用ApplicationContext。我究竟做错了什么?如果我将变量getIpaddressNC, getIpaddressOM设为静态,则auto wiring可以工作,如果oim在应用程序加载时为variables,则initialized via setters返回null。

最佳答案

您同时为OidDao使用了组件扫描和手动接线。您在xml配置中定义了oidDao,如下所示:

<bean id="oidDao" class="com.simulator.service.OidDao">
        <property name="ipaddressNC" value="${ipaddressNC}" />
        <property name="ipaddressOM" value="${ipaddressOM}" />
</bean>


然后,在Component上添加OidDao批注,如下所示:

@Component
public class OidDao implements OidManager {
...
}


删除Component注释,您会没事的!因为否则,<context:component-scan base-package="com.simulator" />将选择OidDao并使用默认构造函数从中实例化一个实例,而无需调用您的setters

10-07 23:48