读书人

一个容易例子和多个bean文件

发布时间: 2012-09-29 10:30:01 作者: rapoo

一个简单例子和多个bean文件
package com.liyixing.spring.service;

import com.liyixing.spring.model.Account;

public interface IAccount {
//删除用户
public void deleteAccount(Account account);
}

定义实现

package com.liyixing.spring.service.imp;

import com.liyixing.spring.model.Account;
import com.liyixing.spring.service.IAccount;

public class AccountService implements IAccount {

public void deleteAccount(Account account) {
System.out.println("删除用户");
}

}


在classpath创建文件beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="accountService" });
IAccount accountService = (IAccount) context.getBean("accountService");

accountService.deleteAccount(new Account());
}

}
这里的Test使用了ClassPathXmlApplicationContext,这个类会从当前的classpath中寻砸坏哦beans.xml,new String[] { "beans.xml" }这里是个数组,可以指定多个spring配置文件。这里已经介绍了一种多个bean文件的使用
Spring团队倾向于上述做法,因为这样各个配置并不会查觉到它们 与其他配置文件的组合。


另外一种方法是使用一个或多个的<import/>元素 来从另外一个或多个文件加载bean定义。所有的<import/>元素必 须在<bean/>元素之前完成bean定义的导入。 让我们看个例子:

<beans>

<import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/themeSource.xml"/>

<bean id="bean1" class="..."/>

</beans>
根据Spring XML配置文件的 Schema(或DTD),被导入文件必须是完全有效的XML bean定义文件,且根节点必须为 <beans/> 元素


读书人网 >软件架构设计

热点推荐