Spring记录

本文介绍了一个使用Spring框架进行Bean注入的例子,包括通过setter方法注入字符串和日期类型的属性,并展示了如何配置Bean定义文件及使用ApplicationContext获取Bean实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[b]Bean HelloBean.java[/b]

package onlyfun.caterpillar;
public class HelloBean
{
private String helloWord;

public void setHelloWord(String helloWord)
{
this.helloWord = helloWord;
}
public String getHelloWord()
{
return helloWord;
}

//注入的是对象,属性参考
public void setDate(Date date)
{
this.date = date;
}
public Date getDate()
{
return date;
}
}


[b]Bean定义文件 bean-config.xml[/b]
可以使用setter injection, construction injection,此处使用setter注入

<?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="dateBean" class="java.util.Date"/>

<bean id="helloBean" class="onlyfun.caterpillar.HelloBean">
<property name="helloWord">
<value>Hello!Justin!</value>
</property>

<property name="date">
<ref bean="dateBean"/>
</property>

<!-- 也可使用内部Bean注入,如下
<property name="date">
<bean id="dateBean" class="java.util.Date"/>
</property>

-->
</bean>
</beans>


[b]BeanFactory[/b]
BeanFactory負責讀取Bean定义文件,管理对象的載入、生成,对象之間的關係維護,負責Bean的生命週期,對於簡單的應用程式來說,使用 BeanFactory就已經足夠,但是若要利用到Spring在框架上的一些功能以及進階的容器功能,則可以使用[u]ApplicationContext[/u]


ApplicationContext context = new
FileSystemXmlApplicationContext("beans-config.xml");
HelloBean hello = (HelloBean) context.getBean("helloBean");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值