Idea創建Spring項目


環境 win7 + Idea2018

Classpath commons-logging-1.2 + spring-framework-4.1.6.RELEASE

Step1 創建工程

File -> New -> Project

選擇Spring項目,“Addtionnal Lib and Frameworks” 選擇第一個 ”Spring”, next 命名項目HelloSpring

Step2 添加jar

選擇項目HelloSpring  File –> Project Structure->Modules,選中項目HelloSpring,選中Dependancies 頁簽,點擊“+” 添加jar包,效果如下

commons-logging-1.1.1

spring-aop-4.1.6.RELEASE

spring-aspects-4.1.6.RELEASE

spring-beans-4.1.6.RELEASE

spring-context-4.1.6.RELEASE

spring-context-support-4.1.6.RELEASE

spring-core-4.1.6.RELEASE

spring-expression-4.1.6.RELEASE

spring-instrument-4.1.6.RELEASE

spring-instrument-tomcat-4.1.6.RELEASE

spring-jdbc-4.1.6.RELEASE

spring-jms-4.1.6.RELEASE

spring-messaging-4.1.6.RELEASE

spring-orm-4.1.6.RELEASE

spring-oxm-4.1.6.RELEASE

spring-test-4.1.6.RELEASE

spring-tx-4.1.6.RELEASE

spring-web-4.1.6.RELEASE

spring-webmvc-4.1.6.RELEASE

spring-webmvc-portlet-4.1.6.RELEASE

spring-websocket-4.1.6.RELEASE

 

 

 

 

 

Step3 創建源代碼

HelloWorld.java MainApp.java

主程序邏輯如下:

public static void main(String[] args) {

      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

      obj.getMessage();

   }

首先適用framework API ClassPathXmlApplicationContext()創建application context,這個API接口會加載beans配置文件,並根據所提供api去創建、初始化對象(即 配置文件中的beans);

其次,使用上步創建的contex getBean()方法獲取對象bean ID,並最終向上cast得到實際對象,進而調用所有對象方法。

Step4 創建bean配置文件

Bean.xml配置文件的功能是將所有的bean粘合在一起;命名可以任意,但必須在ClassPath路徑配置,並且創建application context時使用的名稱一致;

Beans.xml 給beans分別指派唯一Id,並且創建對象時可以傳入參數值,例如“message”變量:

<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld">

      <property name = "message" value = "Hello World!"/>

   </bean>

Step5 運行程序

控制台輸出

Your Message : Hello World!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM