spring環(huán)境搭建步驟

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對象
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容