1、導入Jar包,目前導入五個基本jar包:
commons-logging-1.2.jar
spring-beans-4.3.10.RELEASE.jar
spring-context-4.3.10.RELEASE.jar
spring-core-4.3.10.RELEASE.jar
spring-expression-4.3.10.RELEASE.jar
2、在src文件夾下新建config文件夾,在config文件夾中新建spring核心配置文件“×××.xml(習慣上命名為:application.xml)”
“application.xml”文件模板:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#overview-distribution-zip
<?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.xsd">
<bean id="..." class=“…”>//id值自定義,class值為Java類的包名+類名
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
實例1:
<?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.xsd">
<bean id="user" class="model.User"></bean>//spring容器默認為在服務器啟動時創(chuàng)建單例User對象,可以添加lazy-init="true”在調(diào)用getBean方法的時候創(chuàng)建User對象,添加scope="prototype”創(chuàng)建多例對象
</beans>
3、新建一個Test類,在main方法中
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml”);//參數(shù)為spring核心配置文件的文件名“application.xml”
Object u = context.getBean("user”);//參數(shù)為“application.xml”配置文件中的id值“user”,獲得一個Object對象
User u1 = context.getBean("user", User.class);//第一個參數(shù)為“application.xml”配置文件中的id值“user”,第二個參數(shù)為Java類的class對象User.class,獲得一個User對象