Spring通过XML文件,完成bean配置和bean间依赖关系的注入。

1.需要用到的包:
spring-core.jar
spring-beans.jar
spring-context.jar
commons-logging.jar

2.Bean文件
HelloBean.java
package cn.blogjava.hello;

import java.util.Date;

public class HelloBean {
    
    
private String helloWord;
    
private String name;
    
private Date date;
    
    
public HelloBean() {
        
    }

    
public HelloBean(String helloWord, String name) {
        
this.helloWord = helloWord;
        
this.name = name;
    }    
    
    
public String getHelloWord() {
        
return helloWord;
    }

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

    
public String getName() {
        
return name;
    }

    
public void setName(String name) {
        
this.name = name;
    }
    
    
public Date getDate() {
        
return date;
    }

    
public void setDate(Date date) {
        
this.date = date;
    }
}

配置文件
beans-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="dateBean" class="java.util.Date"/>
    
<bean id="helloBean" class="cn.blogjava.hello.HelloBean" >
        
<property name="helloWord">
            
<value>Hello!</value>
        
</property>
        
<property name="name">
            
<value>YYY!</value>
        
</property>    
        
<property name="date">
            
<ref bean="dateBean" />
        
</property>                
    
</bean>
</beans>

3.测试程序
SpringDemo.java
package cn.blogjava.hello;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class SpringDemo {
    
public static void main(String[] args) {
        ApplicationContext context 
= 
            
new FileSystemXmlApplicationContext("beans-config.xml");        
        HelloBean helloBean 
= (HelloBean)context.getBean("helloBean");
        System.out.print(
"Name: ");
        System.out.println(helloBean.getName());
        System.out.print(
"Word: ");
        System.out.println(helloBean.getHelloWord());
        System.out.println(helloBean.getDate());
    }
}
posted on 2006-07-26 10:09 knowhow 阅读(368) 评论(0)  编辑  收藏 所属分类: Framework

只有注册用户登录后才能发表评论。


网站导航: