Spring框架學習-搭建第一個Spring項目
步驟一:下載Spring開發包。
官網:https://spring.io/ 下載地址:https://repo.spring.io/libs-release-local/org/springframework/spring/
spring-framework-3.0.2.RELEASE-dependencies和spring-framework-4.2.4.RELEASE-dist 解壓第二個,解壓目錄:
步驟二:搭建項目,引入Spring項目
創建項目:由於Spring是JavaSE/EE一站式框架,所以既可以創建web項目或者java項目,這裏創建web項目。
導入jar:Spring框架搭建肯定需要核心包,上面Core Container裏面四個就是核心,其他的,需要什麽功能添加哪個jar,在libs裏面找。還有spring已經弄好的日誌記錄包,在dependencies裏面log4j和commons包下
步驟三:引入相關配置文件(在src下創建)
log4j.properties
### direct log messages to stdout ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.err log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file mylog.log ### log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.File=c\:mylog.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change ‘info‘ to ‘debug‘ ### # error warn info debug trace log4j.rootLogger= info, stdout
applicationContext.xml文件(Spring的核心配置文件)
頭部引入:在解壓下來的spring-framework-4.2.4.RELEASE-dist\docs\spring-framework-reference\html\xsd-configuration.html裏面就有配置文件頭部schema約束
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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"> <!-- 配置,將實現類的對象創建交給Spring管理 bean標簽: id:給bean起個名字,唯一,不能重復,不能出現特殊字符,就看做根據面向接口編程new出來的實例 class:類的全路徑,底層根據全路徑生成實例 --> <bean id="userDao" class="cn.xxx.dao.impl.UserDaoImpl"> <!-- 屬性依賴註入,底層會自動封裝,只要在dao實現類提供屬性和set方法就行 --> <property name="name" value="張三"></property> </bean> </beans>
UserDaoImpl.java(UserDao接口的實現)
package cn.xxx.dao.impl; import cn.xxx.dao.UserDao; /** *@param *@author cxh */ public class UserDaoImpl implements UserDao { private String name; public void setName(String name) { this.name = name; } @Override public void insert() { System.out.println(name+"用戶信息插入"); } }
測試類:
@Test public void demo1() { // 通過加載配置文件創建Spring工廠類(框架默認加載路徑在src下,所以完全可以將配置文件放在一個目錄下) ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/config/applicationContext.xml"); // 通過工廠來解析XML獲取Bean的實例 UserDao userDao = (UserDao) applicationContext.getBean("userDao"); userDao.insert(); }
運行結果:
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment). log4j:WARN Please initialize the log4j system properly. 張三用戶信息插入
上面就是基於Spring的IOC的搭建。
IOC:控制反轉,將對象的創建權交給Spring
DI:依賴註入,前提必須有IOC的環境,Spring在管理這個類的時候順便會註入類的依賴的屬性。
Spring框架學習-搭建第一個Spring項目