一个简单例子和多个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" class="com.liyixing.spring.service.imp.AccountService">
</bean>
</beans>

测试
package com.liyixing.spring.test;

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

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

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "beans.xml" });
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="..."/>
    <bean id="bean2" class="..."/>

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


猜你喜欢

转载自liyixing1.iteye.com/blog/1036515