Spring IoC容器的基础都在 org.springframework.beans 和 org.springframework.context 包中。提供了2类容器实现:org.springframework.beans.factory.
BeanFactory 和 org.springframework.context.
ApplicationContext,主要使用的是
ApplicationContext
经常使用的3个ApplicationContext的实现:
ClassPathXmlApplicationContext,
FileSystemXmlApplicationContext,
XmlWebApplicationContext
ApplicationContextcontext=new FileSystemXmlApplicationContext("c:/foo.xml");
ApplicationContextcontext=new ClassPathXmlApplicationContext("foo.xml");
Spring 配置文件基础,一个典型的配置文件:
<?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-3.1.xsd">
<import resource=”resource1.xml”/>
<!-- oracle bean used for a few examples -->
<bean id="oracle" name= "wiseworm" class="com.apress.prospring3.ch4.BookwormOracle" />
</beans>
import用于导入其他配置文件,<import>标签可以放在<beans>下的任何位置,没有顺序关系。可以使用下面格式:
file:C:/config/services.xml
classpath:/config/services.xml
Spring 提供的命名空间:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"xmlns:c="http://www.springframework.org/schema/c"xmlns:util="http://www.springframework.org/schema/util"xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsdhttp://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-3.1.xsd">
</beans>
ApplicationContext context = new
ClassPathXmlApplicationContext(
new String[] {"services.xml", "daos.xml"});
PetStoreServiceImpl service = context.getBean("petStore", PetStoreServiceImpl.class);
List userList = service.getUsernameList();
public
class
DeclareSpringComponents {
public
static
void
main(String[] args) {
GenericXmlApplicationContext ctx =
new
GenericXmlApplicationContext();
ctx.load(
"classpath:app-context-xml.xml"
);
//ctx.load("classpath:app-context-annotation.xml");
ctx.refresh();
MessageProvider messageProvider = ctx.getBean(
"messageProvider"
, MessageProvider.
class
);
System.
out
.println(messageProvider.getMessage());
}
}