当前位置: 代码迷 >> J2EE >> 关于简单的spring3.x的自动装载autowire,该如何解决
  详细解决方案

关于简单的spring3.x的自动装载autowire,该如何解决

热度:18   发布时间:2016-04-22 02:18:25.0
关于简单的spring3.x的自动装载autowire
不能自动加载。我如果给bean加一个构造函数,设置autowire="constructor"的时候可以,但是去掉构造函数,设置为autowire="byName"或者autowire="byType"的时候,不能自动加载,在控制台输出为null。下面是代码

bean代码:
Java code
package com.gc.action;import java.util.Date;public class HelloWorld {    public String msg=null;    public Date date=null;        public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }    public Date getDate() {        return date;    }    public void setDate(Date date) {        this.date = date;    }    public HelloWorld(Date date){        this.date=date;    }}


xml代码:
Java code
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><beans>    <bean id="HelloWorld" class="com.gc.action.HelloWorld" autowire="byName">        <property name="msg">            <value>1111</value>        </property>    </bean>    <bean id="date" class="java.util.Date"></bean></beans>


测试代码:
Java code
package com.gc.test;import java.io.FileNotFoundException;import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;import com.gc.action.HelloWorld;public class TestHelloWorld {    /**     * @param args     * @throws FileNotFoundException      */    public static void main(String[] args) throws FileNotFoundException {        // TODO Auto-generated method stub        ApplicationContext actx=new FileSystemXmlApplicationContext("config.xml");        HelloWorld helloWorld=(HelloWorld)actx.getBean("HelloWorld");        System.out.println(helloWorld.getDate()+":"+helloWorld.getMsg());            }}


输出:
null:1111


请指教。

------解决方案--------------------
这个是bean的自动加载...... 你至少要保证spring里面有你所对应名称的bean撒 意思就是msg和date的bean撒
------解决方案--------------------
是这么配的。
你贴出来的东西,除了HelloWorld少无参构建器之外,其他并没有问题。
  相关解决方案