Spring學習資料以及配置環境

1、Spring4 一、介紹 新特性 SpringIDE 插件 IOC DI 在 Spring 中配置 Bean 自動裝配 Bean 之間的關係(依賴、繼承) Bean 的做用域 使用外部屬性文件 SpEL 管理 Bean 的生命週期 經過工廠方法配置 Bean 經過 FactoryBean 配置 Bean 經過註解配置 Bean 泛型依賴注入 AOP 基礎 前置通知 後置通知 返回通知 異常通知 環繞通知 切面的優先級 切點表達式 使用 XML 文件的方式配置 AOP 使用 JdbcTemplate 和 JdbcDaoSupport 使用 NamedParameterJdbcTemplate Spring 的聲明式事務 事務的屬性(傳播行爲、隔離級別、回滾屬性、只讀屬性、過時時間) 使用 XML 文件的方式配置事務 整合 Hibernate 整合 Struts2 等。 二、安裝maven 一、電腦須要有Java環境 輸入java -version 驗證 二、下載maven http://maven.apache.org/download.cgi 選擇編譯過的版本 apache-maven-3.5.0-bin.zip 解壓到D盤 D:\mvn3.5\apache-maven-3.5.0 三、配置環境變量 新建環境變量 M2_HOME=D:\mvn3.5\apache-maven-3.5.0 添加PATH ;%M2_HOME%\bin; 驗證 mvn -v 四、修改Maven倉庫路徑 如改成 d:\m2\repository 修改配置文件 D:\mvn3.5\apache-maven-3.5.0\conf\settings.xml 找到localRepository標記 修改成 D:/m2/repository 注意斜線與linux相同 把settings.xml 文件複製到D:/m2 下 五、maven目錄介紹 bin 放置命令文件夾 boot 啓動文件夾 默認類加載器 conf 配置文件夾 settings.xml 全局定製maven行爲 lib maven運行須要的類庫 六、eclipse中安裝maven插件 須要網絡 help --》 Install new software --》 add 在name輸入 m2e 在Location 輸入 http://download.eclipse.org/technology/m2e/releases 選中 search到Maven插件 依次點擊next 重啓eclipse 插件安裝成功驗證 在Window--》Preferences --》 多了一個Maven選項 七、eclipse中配置maven 在Window--》Preferences --》 Maven選項 點擊 Installations 添加本身的maven 點擊 User Settings 選擇本身的settings.xml 文件 八、工程目錄分析 src/main/java java源文件 src/test/java 測試類位置 Maven Dependencies maven依賴的jar文件 target maven編譯後文件位置 pom.xml 全稱Project Object Model 項目基本信息 src 存放main和test會用到的第三方資源 九、打包 在pox.xml 中 jar 指定打包類型 默認是jar 在項目的根路徑下 mvn package 打包 mvn clean 清理包 驗證 查看target目錄 十、maven建立項目 一、Archetype quickstart 普通java項目 打jar包 webapp web項目 打war包 二、新建webapp項目 一、在項目嚮導中創建項目 Archetype 選 webapp 二、給項目添加Server Runtime支持 右鍵項目--》屬性--》java build --》 add library --》Server Runtime --》tomcat8 三、查看Deployment Assemb... 肯定/src/main/webapp / 三、項目目錄介紹 src/main/java 放置java源文件位置 src/main/webapp web根路徑 放置前臺文件位置 三、安裝 eclipse spring插件 須要網絡 help --》 Install new software --》 add 選擇本地的springsource-tool-suite-3.8.4.RELEASE-e4.6.3-updatesite.zip 選擇帶IDE的四個選項 下一步 下一步 贊成 完成。 重啓eclipse 驗證 window 首選項中有spring 四、給項目添加spring IOC支持 在pox.xml文件中 添加 org.springframework spring-web 4.0.2.RELEASE 追加jar包 8個 spring-web-4.0.2.RELEASE.jar spring-aop-4.0.2.RELEASE.jar aopalliance-1.0.jar spring-beans-4.0.2.RELEASE.jar spring-context-4.0.2.RELEASE.jar spring-expression-4.0.2.RELEASE.jar spring-core-4.0.2.RELEASE.jar commons-logging-1.1.3.jar org.springframework spring-context 4.0.2.RELEASE 追加jar包 7個 spring-context-4.0.2.RELEASE.jar spring-aop-4.0.2.RELEASE.jar aopalliance-1.0.jar spring-beans-4.0.2.RELEASE.jar spring-core-4.0.2.RELEASE.jar commons-logging-1.1.3.jar spring-expression-4.0.2.RELEASE.jar 重合7個,只需引入一個便可 五、HelloWorld 什麼是bean 有無參構造器,有set,get方法的就是bean 一、寫一個HelloWorld.java public class HelloWorld { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void hello(){ System.out.println("hello "+name); } } 二、寫一個配置文件applicationContext.xml,配置類 三、在主方法中,寫代碼 ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml"); 這句話是獲取IOC容器,這個時候會把全部的bean都初始化,並set給屬性賦值 HelloWorld he = (HelloWorld) ac.getBean("helloWorld"); 獲取被管理的bean he.hello(); 調用業務方法 六、 IOC和DI 傳統 是你要,我給 ioc 你不用要,我給 DI 給的方式 七、配置Bean bean必須有無參構造器,反射方式建立。 id 容器中類的惟一 能夠有多個名字,用逗號分隔。 ApplicationContext 表明IOC容器 BeanFactory 基礎設置,面向spring自己 BeanFactory ac= new ClassPathXmlApplicationContext("applicationContext.xml"); ApplicationContext 面向開發者 ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml"); ClassPathXmlApplicationContext 從類路徑查找 FileSystemXmlApplicationContext 從文件系統查找 BeanFactory ac= new FileSystemXmlApplicationContext("C:\\Users\\Administrator\\workspace3\\testmaven3\\src\\main\\resources\\applicationContext.xml"); getBean 經過id 推薦用 HelloWorld he = (HelloWorld) ac.getBean("helloWorld"); 經過class 不推薦,不肯定有幾個class對象。 HelloWorld he = ac.getBean(HelloWorld.class); 基於xml 基於註解 八、注入方式 屬性注入 構造注入 位置 類型 區分重載的構造器 工廠方法注入(不經常使用)知道就可 屬性注入細節 基本數據類型+String 1\ 2\ Rose 3\ 4\ jack 五、包含特殊符號 <hahaha> 對象類型 引用對象類型 內部bean 不用id,只能在內部使用 <hehehe> null值和級聯屬性 null值 級聯屬性 屬性先初始化後纔可級聯處理。struts2 不同 集合屬性 Set t1 t2 t3 Array t1 t2 t3 List t1 t2 t3 Map Properties t1 t2 t3 配置公用的集合 一、引入util命名空間 二、獨立集合 t1 t2 t3 三、 ref="carss" 引用集合 使用p命名空間 一、引入p命名空間 二、使用p 比之前代碼更加簡潔 自動裝配 autowire="byName" 經過名稱裝配 id名稱和類屬性名稱一致,set方式裝配 autowire="byType" 經過類型裝配 相同類型的bean只能有一個 一、要裝配都裝配 二、byName ,byType只能2選1 Bean之間的關係 繼承 parent="car" 不是java中的繼承,就是利用以前bean的配置模板,快速生成新的bean,繼承後,只寫不一樣的屬性。 不是全部屬性都會被繼承 如 autowire 、abstract等 abstract="true" 抽象bean 不能實例化 只能被繼承 能夠不指定class屬性,沒有class屬性的bean必定是抽象bean 依賴 depends-on="car" 用逗號,指定多個bean bean的加載自己沒有順序,經過depends-on 來肯定前後順序 Bean的做用域 默認單例的,用的都是一個實例。 scope="singleton" 加載容器時建立 非單例模式 scope="prototype" 每次請求時加載(懶) 使用外部屬性文件 spring 2.5以後 九、spel表達式 用#{表達式} 表達式 能夠是直接常量 字符串用'' 動態賦值 能夠是其餘bean的id 相似於ref 其餘bean的屬性 id.shuxing 能夠調用id.方法 能夠經過 T() 調用靜態屬性 能夠用正則 能夠用 +-*/ % 能夠用 > >= < <= == != 能夠用 and or 能夠用 ?: 十、bean的生命週期 一、容器 二、生命週期 init-method="" 初始化方法 destroy-method="" 銷燬方法 ac.close(); destroy-method 方法會被調用 十一、後置處理器 給部分屬性賦值,檢查屬性賦值狀況,處理全部的bean 沒有id public class MyBeanPost implements BeanPostProcessor 在init-method 方法先後被調用 十二、Bean的配置方式 工廠方法 靜態工廠方法 獲取bean對應的工廠產生的某一個實例 id 指工廠方法中的某一個實例 class 指向靜態方法 factory-method="getCar" 指向靜態方法名 給靜態方法傳參數 實例工廠方法 須要建立工廠類對象 工廠類 經過工廠類建立的對象 沒有class屬性 factory-method="getCar" 指向工廠方法 參數 factory-bean="factory" 指向工廠類id FactoryBean 建立bean spring 提供的 定義一個類,實現FactoryBean 接口 實現三個方法 配置Bean 其餘正常使用。 實際調用 factory的getObject方法 1三、基於註解配置bean @Component 標識一個受Spring管理的組件 @Resposityor 標識持久層 @Service 標識服務層 @Controller 標識控制層 能夠混用 一、配置bean 組件掃描 掃描包 context:commpnent-scan 掃描後,自動生成bean resource-pattern="an/*.class" 指定掃描的資源 包含哪些資源 能夠有多個 不包含哪些資源 能夠有多個 使用默認的規則 use-default-filters="true" annotation 經過註解過濾 assignable 指定接口或者類 在bean上添加註解 二、自動裝配屬性 context:commpnent-scan 掃描時自動裝配 @Autowired 類型兼容的bean,直接加進來 寫在屬性或者set方法上面 寫在屬性上面,不用set方法 不驗證元素必須被管理(沒bean) @Autowired(require=false) 兩個匹配類型 @Autowired 找名字匹配 一個是類型,多個用名字 @Qualifier 這個註解能夠提供Bean名稱,與@Autowired 一塊兒用 @Resource @Inject 1四、泛型依賴注入 父類創建關聯類型 父類用T 泛型 @Autowired 放在屬性上面,能夠被子類繼承,屬性受保護以上修飾 子類繼承這個關係 子類具體類型 子類不寫父類繼承的屬性 2、AOP AOP 是面向切面編程,如日誌等功能。 一、動態代理 log案例 方法內部,proxy不要使用 引入案例 二、AspectJ 的AOP 添加支持 org.springframework spring-aop 4.0.2.RELEASE org.aspectj aspectjrt 1.6.11 org.aspectj aspectjweaver 1.6.11 runtime 三、AOP 註解方式: 0、在applicationContext.xml的配置 添加 一、寫一個類,寫before方法 二、在類中添加另個註解,一個被ioc管理,一個做爲aop的切面 @Aspect @Component 三、在方法上寫 @Before("execution(public int com.ibc.aop.test1.IComputer.add(int,int))") @Before("execution(public int com.ibc.aop.test1.IComputer.*(int,int))") * 表示全部方法 .. 表示參數任意 在方法中能夠獲取方法名和參數 point.getSignature().getName() point.getArgs() 四、後置通知,不管方法是否有異常,都會被執行。 不能訪問方法執行的結果 @After("execution(public int com.ibc.aop.test1.IComputer.*(int,int))") 五、返回通知, @AfterReturning ,能夠有返回值,有異常不執行 @AfterReturning(value="execution(public int com.ibc.aop.test1.IComputer.add(int,int))",returning="ret") public void afterMethod(JoinPoint point,Object ret){ } 六、異常通知, 有異常纔會出現 @AfterThrowing(value="execution(public int com.ibc.aop.test1.IComputer.add(..))",throwing="ex") public void afterThrowMethod(JoinPoint point,Exception ex){} 異常類型,能夠決定什麼異常能夠被通知。 七、環繞通知, 環繞通知須要攜帶ProceedingJoinPoint類型參數 至關於一個完整的動態代理 環繞通知必須有返回值,即目標方法必須有返回值 @Around(value="execution(public int com.ibc.aop.test1.IComputer.add(..))") public Object aroundMethod(ProceedingJoinPoint point){ Object proceed =null; try { //前置 Signature signature = point.getSignature(); System.out.println("method -----@aroundMethod "+signature.getName()+" "+Arrays.toString(point.getArgs())); proceed = point.proceed(); //返回通知 } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); //異常通知 } //後置通知 return proceed; } 八、驗證切面 若是有多個切面,能夠設置切面的優先級 @Order(1) 數據越小優先級越高 九、重用切點表達式 定義一個模板方法 @Pointcut @Pointcut("execution(public int com.ibc.aop.test1.IComputer.add(..))") public void declareJoinPaint(){} 在類內切點方法上 @After("declareJoinPaint()") public void afterMethod(JoinPoint point){} 在類外方法上 @After("LoggingAspect.declareJoinPaint()") public void afterMethod(JoinPoint point){} 十、基於xml方式 十一、JDBCTemplate 一、導入jar包 org.springframework spring-jdbc ${spring.version} 二、配置 三、操做 ApplicationContext ac=new ClassPathXmlApplicationContext("application-mysql.xml"); JdbcTemplate ds=(JdbcTemplate) ac.getBean("jdbcTemplate"); 一、單sql的增刪改 int m= ds.update("delete from user where id=?",2); 二、批量增長 List params=new ArrayList (); params.add(new Object[]{2}); //List int[] i=ds.batchUpdate("delete from user where id=?", params); 三、查詢單條記錄 String sql="select id,uname from user where id=?"; RowMapper rowMapper=new BeanPropertyRowMapper (User.class); User user = ds.queryForObject(sql, rowMapper, 1); 用sql的別名 實現列於屬性之間的映射 不支持級聯屬性 四、查詢出集合 String sql="select id,uname from user where id>?"; RowMapper rowMapper=new BeanPropertyRowMapper (User.class); List list=(List ) ds.query(sql, rowMapper,0); 五、獲取單個屬性值 String sql="select count(*) from user"; Long m = ds.queryForObject(sql, Long.class); 十二、具名參數JDBCTemplate 維護性高,不用對參數 一、配置 沒有無參構造器 二、使用 NamedParameterJdbcTemplate ds=(NamedParameterJdbcTemplate) ac.getBean("namedParameterJdbcTemplate"); Map map =new HashMap<>(); map.put("un", "Rose"); //un 就是具名, 在sql中寫 :un int i = ds.update("insert into user(uname) values(:un)",map); 能夠像hiberante那樣操做,存對象 參數名要與屬性名一致 NamedParameterJdbcTemplate ds=(NamedParameterJdbcTemplate) ac.getBean("namedParameterJdbcTemplate"); String sql="insert into user(uname) values(:uname)"; User user=new User("tatata"); SqlParameterSource paramSource=new BeanPropertySqlParameterSource(user); int i =ds.update(sql, paramSource); 1三、事務 一、聲明式事務 一、添加事務依賴 org.springframework spring-tx ${spring.version} 二、在xml配置文件中,添加事務管理 三、在service方法上面添加註解 @Transactional 二、事務傳播行爲 一個事務方法調用另一個事務方法,就是事務傳播 required 若是有事務在運行,就在這個事務中工做,若是沒有 則新建一個事務,運行。 在事務中運行。 在對應方法上 @Transactional(propagation=Propagation.REQUIRED) required_new 若是有事務在運行,掛起事務,而後新建事務運行, 若是沒有事務,則運行新事物。 在本身的事務中運行。 在對應方法上 @Transactional(propagation=Propagation.REQUIRES_NEW) 三、事物的隔離級別 在對應方法上 @Transactional(propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED) 四、默認,對全部運行時異常進行回滾 一般用默認值 @Transactional(rollbackFor={IOException.class},noRollbackFor={SQLException.class}) rollbackFor 回滾的異常類型數組 noRollbackFor 不回滾的異常類型數組 五、是否只讀事務,幫助數據庫引擎優化 @Transactional(readOnly=true) 六、回滾前最多須要多少時間,單位秒 @Transactional(timeout=3) 能夠用sleep方法測試,單位毫秒。 ----- 七、基於xml的方式 在配置文件中配置 --- 回滾的異常類型數組 1四、spring整合hibernate4 Spring管理SessionFactory hibernate用spring的事務管理 一、添加支持 org.hibernate hibernate-core ${org.hibernate-version} commons-dbcp commons-dbcp 1.4 org.springframework spring-hibernate 1.2.9 二、添加配置文件 1五、在eclipse中添加hibernate插件 一、hibernate Tools 的離線安裝 肯定eclipse的版本是neon help --》 Install new software --》 add 在Location 輸入 選擇本地的插件 jbosstools-4.4.4.Final-updatesite-core.zip 點擊JBoss Web and Java EE Development 選擇Hibernate Tools 打√, 取消Contact all update sites during install to find required software 依次點擊next 重啓eclipse 二、hibernate.cfg.xml 數據源移到spring中 關聯的hbm.xml 移到spring中 須要配置 hibernate的基本屬性:方言,SQL顯示格式化,生成數據表的策略以及二級緩存等。 1六、能夠不用hibernate.cfg.xml org.hibernate.dialect.MySQLDialect true true update 1七、spring 整合 Struts2 經過監聽器整合 ServletContextListener 裏面建立ApplicationContext 比較合適。 一、添加jar包 org.springframework spring-web 4.0.2.RELEASE org.springframework spring-core 4.0.2.RELEASE 二、寫一個ServletContextListener 建立一個ApplicationContext對象, 放入ServletContext範圍中 能夠創建一個Context-param 把配置名稱導入進來。 三、建立一個Servlet,在Servlet中獲取AC,而後得到bean,作輸出。 1八、spring 在web中應用 一、在web.xml中 添加一個context-param contextConfigLocation classpath:applicationContext.xml 二、配置ioc org.springframework.web.context.ContextLoaderListener 三、在jsp中 ApplicationContext ac=WebApplicationContextUtils.getWebApplicationContext(application); 1九、spring 集成struts2 管理struts2的anction 一、添加jar包 org.apache.struts struts2-core 2.3.16.3 org.apache.struts struts2-spring-plugin 2.3.16.3 二、在web.xml中 注意:struts.xml 默認是放在src的類路徑下,如今我把它放在/WEB-INF/ 下了,另外,須要額外添加 struts-default.xml,struts-plugin.xml 兩個配置信息。 ***這是web容器鏈接struts2的鏈接點 配置的Action默認後綴是 .action struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter config struts-default.xml,struts-plugin.xml,../struts.xml struts2 /* 二、 在applicationContext.xml中配置Action beans 注意添加屬性 scopt=prototype 表示不是單例的 三、 在struts.xml中的action中的class屬性配置 spring bean的id /ok.jsp 注意 class="helloAction" 與 id="helloAction" 相同 20、spring 集成springmvc 一、添加jar包 org.springframework spring-core 4.0.2.RELEASE org.springframework spring-webmvc 4.0.2.RELEASE 二、在web.xml中配置springmvc springDispatcherServlet org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:springmvc.xml 1 springDispatcherServlet / 三、定義springmvc.xml文件 掃描IOC類 統一處理方法返回值先後綴 四、定義一個類用@Controller修飾,表示自動被掃描 定義一個帶String返回值的方法 用@RequestMapping("/helloworld") 修飾 表示url地址 @Controller public class HelloWorld { @RequestMapping("/helloworld") public String sayHello(){ System.out.println("Hello MVC"); return "success"; } } [訪問用helloworld.do] 返回頁面 prefix+"success"+ suffix 作轉發操做 五、index.jsp http://www.javashuo.com/tag/helloworld 2一、spring集成mybatis 一、添加jar包 mysql mysql-connector-java 5.1.18 org.springframework spring-jdbc 4.0.2.RELEASE c3p0 c3p0 0.9.1.2 org.mybatis mybatis 3.4.1 org.mybatis mybatis-spring 1.3.0 二、編寫 com.ibc.test.User 類 注意,要求序列化 @Component public class User implements Serializable{ private Integer id; private String uname; ...... } 三、編寫User-sqlmap-mapping.xml insert into user(uname) values(#{uname}) UPDATE USER SET uname=#{uname} WHERE ID=#{id} DELETE USER WHERE ID=#{id} 四、編寫 mybatis.xml 五、編寫 db.properties url=jdbc:mysql:///test user=root password=root driver=com.mysql.jdbc.Driver 六、編寫spring.mybatis.xml 文件 classpath:db.properties 七、測試類 ApplicationContext ac=new ClassPathXmlApplicationContext("spring.mybatis.xml"); SqlSessionTemplate sqlSessionTemplate= (SqlSessionTemplate) ac.getBean("sqlSessionTemplate"); List list = sqlSessionTemplate.selectList("queryAll"); System.out.println(list); 2二、配置文件相關的註解方法 一、定義一個類 @Configuration 表示這個類是一個相似於ApplicationContext.xml的類文件 @ComponentScan("com.ibc.ssm") //表示IOC要掃描的包 public class Config { } 二、測試 ApplicationContext ac=new AnnotationConfigApplicationContext(Config.class); User user=ac.getBean(User.class); System.out.println(user); 號外: 經過註解方式定義AOP切面 一、寫一個配置類 @Configuration @ComponentScan("com.ibc.demo") @EnableAspectJAutoProxy public class Config {} 二、定義一個切面 @Component @Aspect public class LogAspect { @Pointcut("execution( * set* (. .))") public void myPointCut(){} @Before("myPointCut()") public void beforeMechod(JoinPoint point){ System.out.println("----beforeMechod--------"+point.getSignature().getName()+" "+point.getArgs()); } } 三、定義一個實體類 @Component public class User implements Serializable { private String username; private Integer uid; private String password; 。。。。。。 } 四、測試類 @Test public void testUser(){ ApplicationContext ac=new AnnotationConfigApplicationContext(Config.class); User user=ac.getBean(User.class); user.setUsername("tom"); System.out.println(user); }
相關文章
相關標籤/搜索