返回信息流我的spring配置文件config.xml如下:
<?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>hello world</value>
</property>
</bean>
<bean id="date" class="java.util.Date"/>
</beans>
有个类HelloWorld.java代码如下:
package com.gc.action;
import java.util.Date;
public class HelloWorld {
private String msg = null;
private Date date = null;
public void setMsg(String msg) {
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setDate(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
}
测试类HelloWorldTest.java代码如下:
package com.gc.action;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
/**
* Hello world!
*
*/
public class HelloWorldTest
{
public static void main( String[] args )
{
// ApplicationContext actx = new FileSystemXmlApplicationContext("config.xml");
BeanFactory factory = new XmlBeanFactory(
new ClassPathResource("config.xml"));
HelloWorld helloWorld = (HelloWorld)factory.getBean("HelloWorld");
System.out.println(helloWorld.getMsg()+helloWorld.getDate());
}
}
下面是官方文档对byName的解释:
Autowiring by property name. This option will inspect the container and look for a bean named exactly the same as the property which needs to be autowired. For example, if you have a bean definition which is set to autowire by name, and it contains a master property (that is, it has a setMaster(..) method), Spring will look for a bean definition named master, and use it to set the property.
大概意思是(我自己的理解):
如果有个bean的autowire=byName,这个bean类里包含了一个类属性(我这里是date,HelloWorld.java里有public void setDate(Date date) ),那么就会自动去找一个叫做date的bean,并给date注入值。
按我的理解,我的程序最后应该能打印出当前日期,可是我的程序只打印出了null。这里没有搞明白为什么。有点长,希望哪位好心人点拨下
这是一条镜像帖。来源:北邮人论坛 / java / #20159同步于 2011/9/21
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
【求助】关于spring bean的byName自动装配
jkfbrant
2011/9/21镜像同步17 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
我的配置文件里有autowire=“byName”
【 在 lovemaker 的大作中提到: 】
: 一种方法是在配置文件里配置
: 另一种方法是加上@autowired注解,不然spring怎么知道这个是普通的属性,还是Bean呢
: --
: ...................
我理解autowire=“byName”只是标识出方式是byName,而属性要不要autowire,需要再次指定,比方说以@autowired注解来指定
【 在 jkfbrant 的大作中提到: 】
: 我的配置文件里有autowire=“byName”
我猜你的msg注入了但是date没注入?你试试获取id为date的bean?应该能打印出来
if so,你的xml好像写错了,hello world这个bean应该有date这个property,并对下面那个bean进行引用
没试过,说错了不负责[ema3]
<bean id="HelloWorld" class="application.example.HelloWorld">
<property name="msg" value="hello world" />
<property name="date" ref="date"/>
</bean>
<bean id="date" class="java.util.Date">
</bean>
去掉autowire=byName,即默认autowire=no,然后加ref就可以正常显示了。
Interesting~
我猜是因为Date的constructor已经deprecated了,所以没办法autowired?
坐等楼下实力解释
【 在 ting0fdnb 的大作中提到: 】
: 也遇到了这个问题,lz解决了么