日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring杂记

發布時間:2024/4/15 javascript 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring杂记 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

基于Spring的項目啟動

  • Download Spring
  • Download Struts2
  • 詳解spring 每個jar的作用
  • Spring API

web.xml加載spring, struts2

<context-param><param-name>contextConfigLocation</param-name><param-value>classpath:/applicationContext.xml</param-value> </context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping><filter-name>struts2</filter-name><url-pattern>*.action</url-pattern> </filter-mapping>

spring-farmework-4.2.4 整合 struts 2.3.24.1

  • @Results( { @Result(name = ActionSupport.SUCCESS, type = "json", params = { "root", "bannerResult", "excludeNullProperties", "true", "enableGZIP", "true" }) })
  • 最少所需依賴包
    • spring-core-4.2.4.RELEASE.jar
    • spring-web-4.2.4.RELEASE.jar
    • spring-context-4.2.4.RELEASE.jar
    • spring-beans-4.2.4.RELEASE.jar
    • spring-aop-4.2.4.RELEASE.jar
    • spring-expression-4.2.4.RELEASE.jar
    • commons-logging-1.2.jar
  • 整合struts 2.3.24.1
    • struts2-spring-plugin-2.3.24.1.jar
    • xwork-core-2.3.24.1.jar
    • struts2-core-2.3.24.1.jar
    • ognl-3.0.6.jar
    • javassist-3.11.0.GA.jar
    • commons-io-2.2.jar
    • commons-fileupload-1.3.1.jar
    • freemarker-2.3.22.jar
    • commons-lang3-3.2.jar
    • struts2-convention-plugin-2.3.24.1.jar Struts2 Annotation
    • asm-3.3.jar
    • struts2-json-plugin-2.3.24.1.jar Use json-default package
    • asm-commons-3.3.jar 需要但有時候不報錯
    • struts2-config-browser-plugin-2.3.24.1.jar /config-browser/actionNames.action
  • applicationContext.xml

    <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:p="http://www.springframework.org/schema/p" xmlns:jee="http://www.springframework.org/schema/jee"xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsdhttp://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-springhttp://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd"><context:annotation-config /><context:component-scan base-package="" /><task:annotation-driven /> <import resource="classpath:/applicationContext_datasource.xml" /><ehcache:annotation-driven cache-manager="ehCacheManager" /><bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" /><bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /><property name="ignoreResourceNotFound" value="true" /><property name="locations"><list><value>classpath:global.properties</value><value>classpath:query.properties</value></list></property></bean></beans>

Spring3.2.9 整合 Hibernate4.2.2

  • spring jar
    • spring-core-3.2.9.RELEASE.jar
    • spring-context-3.2.9.RELEASE.jar
    • spring-beans-3.2.9.RELEASE.jar
    • spring-orm-3.2.9.RELEASE.jar
    • spring-tx-3.2.9.RELEASE.jar
    • spring-jdbc-3.2.9.RELEASE.jar
    • spring-expression-3.2.9.RELEASE.jar
    • spring-aop-3.2.9.RELEASE.jar
  • hibernate jar
    • hibernate-core-4.2.2.Final.jar
    • hibernate-commons-annotations-4.0.2.Final.jar
    • hibernate-jpa-2.0-api-1.0.1.Final.jar
  • other jar
    • dom4j-1.6.1.jar
    • javassist-3.11.0.GA.jar
    • jboss-logging-3.1.0.GA.jar
    • aopalliance-1.0.jar
  • and maybe there are smoe other jars not know because they are in project already

  • applicationContext.xml

  • dataSource

    <bean id="orcaleDS" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property><property name="url" value="${xxx.url}"></property><property name="username" value="${xxx.user}"></property><property name="password" value="${xxx.DB.password}"></property></bean>
  • sessionFactory
    packagesToScan 需要spring3,2.5不支持

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><property name="dataSource" ref="orcaleDS" /><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop><prop key="hibernate.show_sql">false</prop><prop key="hibernate.format_sql">true</prop><prop key="javax.persistence.validation.mode">none</prop></props></property><property name="packagesToScan"> <list> <value>com.xxx.pojo</value> </list> </property> </bean>
  • transactionManager
    @Transcation 需要annotation-driven才會生效

    <tx:annotation-driven/><bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean>

Junit4 and Mokito 與Spring整合

Junit4 和 Spring整合,用Spring IOC來管理Test Case,從而實現Test Case可利用Spring強大的事物管理等功能,實現Test Case對數據庫操作回滾的功能,保持數據庫的完整性。

Mockito能有效的mock那些測試類中的不可控的對象,比如Request和Response

注解的方式整合Spring : extends AbstractTransactionalJUnit4SpringContextTests

@ContextConfiguration(locations={"config/applicationContext-datasource-test.xml","config/applicationContext-Freedom-test.xml","classpath:applicationContext-grid.xml","classpath:applicationContext-Freedom-legacy.xml" })

實現事物回滾

@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)

Mockito

  • MockitoAnnotations.initMocks(this);
    • 使Mockito的注解生效,如果不用SpringTest跑test case,可以用@RunWith(MockitoJUnitRunner.class)代替
  • @Mock 和 @InjectMocks
  • @mock為一個interface提供一個虛擬的實現,成為一個mock對象。
  • @InjectMocks將本test類中的mock(或@mock)注入到被標注的對象中去,也就是說被標注的對象中需要使用標注了mock(或@mock)的對象。但是被標注的對象不是一個mock對象
  • @Spy:可用于實現部分mock
    • @Mock的對象只有在調用了Mockito.when(obj.doSomething()).thenCallRealMethod()的時候才會調用真實方法
    • 而@Spy注解的對象只有在調用了Mockito.when(obj.doSomething()).thenReturn(rtnValue)的時候才返回mock的值,但是真實方法還是會運行
    • 直接返回mock后的值而運行原方法:Mockito.doReturn(true).when(obj).doSomething();

mock Request和Response

protected HttpServletResponse getReponseWithPrintWriter() throws IOException {PrintWriter writer = org.mockito.Mockito.mock(PrintWriter.class);HttpServletResponse response = org.mockito.Mockito.mock(HttpServletResponse.class);org.mockito.Mockito.when(response.getWriter()).thenReturn(writer);return response; }protected HttpServletResponse getReponseWithOutputStream() throws IOException {ServletOutputStream outputStream = org.mockito.Mockito.mock(ServletOutputStream.class);HttpServletResponse response = org.mockito.Mockito.mock(HttpServletResponse.class);org.mockito.Mockito.when(response.getOutputStream()).thenReturn(outputStream);return response; } protected HttpServletRequest getUserIdFromPortalWithMockedRequest() {HttpServletRequest request = org.mockito.Mockito.mock(HttpServletRequest.class);org.mockito.Mockito.when(request.getHeader("user")).thenReturn("sxq");return request; }

其他

  • @Autowired注入Action
  • System.setProperty("SERVER_ENV", "DEV");設置環境變量

Spring AOP

  • Maven dependency
  • aspectjrt.jar
  • aspectjtools.jar
  • @Aspect [切面]
  • 一個切面包括了代理類和目標類
  • 無法被掃描,需要加上@Component,或者把@Aspect加入到掃描列表中
  • Aspect 類上面除了@Aspect和@Component注解外,不能添加某些其他spring annonation,比如@RefreshScope,否則會造成@Around通知的point.proceed();方法也被代理,代理方法執行兩次
  • @Pointcut [切入點]
  • spring的所有切入點都是方法
  • execution : 聲明切入點為某些方法
  • pointcut="(execution * com.*.service..*.fetch(..))"
  • 第1個星 : 任意返回值類型
  • 第2個星 : 任意包
  • 第3個星 : 任意類
  • .. : 第一個點表示目錄分隔,第二個點表示類
  • within : 聲明切入點為某些類的所有方法
  • @annotation : 聲明切入點為某些annonation
  • Annotation需要被掃描
  • bean
  • spring bean的名字
  • Advice [通知]: 代理方法
  • @Before/@After
  • @AfterReturning
  • returnning="result" : 定義返回值為參數
  • @AfterThrowing
  • throwing="e" : 定義異常為參數
  • @Around
  • this="thisBean" : 定義代理類為參數,并且也起到聲明切入點的作用
  • target="targetBean" : 定義目標類為參數,就是被代理類,并且也起到聲明切入點的作用
  • args="(arg0,arg1)" : 定義參數,并且也起到聲明切入點的作用
  • @Orderd(1)
  • 多個通知的順序,默認0
  • 引入(Introduction)
  • @DeclareParents :將代理方法實現某個接口

Spring Data JPA

  • 對JPA規范的封裝,可以使用Hibernate的JPA實現,還可以切換到其他JPA實現
  • public interface BondLevelsLiveRepository extends JpaRepository < BondLevelsLivePojo, BondLevelsLivePojoId >
  • @Modifying : 完成修改操作(注意:不支持新增)
  • @Query("delete from BondLevelsLivePojo pojo where pojo.lastUpdated < :date")
  • void deleteStaleEntities(@Param("date") Date date);
  • Spring Scheduler

    • @Scheduled與@Async合用的時候,不管前一個任務又沒有完成,都會再起一個線程開始新的任務
    • @Scheduled默認單線程,可以通過設置線程池的個數來達到多現成的需求

      @Configurationpublic class SchedulerConfiguration implements SchedulingConfigurer {@Overridepublic void configureTasks(ScheduledTaskRegistrar taskRegistrar) {ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();taskScheduler.setPoolSize(20);taskScheduler.initialize();taskRegistrar.setTaskScheduler(taskScheduler);}}

    Spring Cache

    Getting Start

    • Maven dependency
    • org.springframework.boot : spring-boot-starter-cache
    • spring-context-x.RELEASE.jar
    • @EnableCaching
    • 可以放在spring boot 啟動類
    • 啟用@Cacheable, @CachePut and @CacheEvict
    • doc : https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#cache
    • CacheManager
    • 不指定CacheManager實現的時候默認使用ConcurrentHashMap

    Spring MVC

    常用Annonation

    • @RestController或者使用@Controller+@ResponseBody
    • @RequestMapping(value = "/springboot/webapi/price/get", method = RequestMethod.GET)
    • PostMapping/GetMapping
    • consumes: 限制接受請求的數據類型(Content-Type),MediaType
    • produces: 限制返回的數據類型(accept)
    • @PathVariable
    • 一般把key放在請求的path里{key}
      @RequestParam(required=false) String ccy
      @ModelAttribute
    • 默認,可以忽略不寫
    • 自動尋找path/param里的參數
      @ResponseStatus
    • 定義返回的狀態碼
      @ControllerAdvice
    • @ExceptionHandler: 相關的Controller的特定Exception會被攔截,又切面同一處理
    • ModelMap可以用于返回多個stiring

    9種Http Method

    • GET : 獲取
    • POST : 添加
    • PUT/PATCH : 修改/部分修改
    • DELETE : 刪除
    • OPTIONS : 獲取可用的協議有哪些
    • HEAD : 只獲取head
    • CONNECT : 維護一次心跳
    • TRACE : 跟蹤

    Reactive 非阻塞式編程

    • Spring MVC 使用java nio實現
    • 直接釋放請求鏈接,等到結果完成后返回Response響應
    • DeferredResult : 返回單個對象
    • ResponseBodyEmitter : 返回一個列表
    • SseEmitter : 支持持續響應Response
    • Spring Web Flex也支持這種操作
    • Spring 很多框架支持Reactive編程,比如Redis等
    • Reactive 編程與java流一起使用

    RestTemplate

    基礎

    • GET
    • getForEntity("http://rates-cache//subject/{1}/{2}/get", String.class, "bond", "key")
    • getForObject : 等同于entity.getBody()
    • POST
    • postForEntity("http://rates-cache//subject/{1}/put?param={2}", subjects, void.class, "bond", "param");
    • postForObject
    • postForLocaltion : 用于提交資源,返回新資源的URI
    • PUT
    • put("http://rates-cache//subject/{1}/put", subjects, "bond"); : 返回void
    • DELETE
    • delete("http://rates-cache//subject/{1}/put", "bond"); : 返回void

    Request Header

    val httpHeaders = HttpHeaders()httpHeaders.contentType = MediaType.APPLICATION_JSON httpHeaders.setBasicAuth("usr","pwd")httpHeaders.accept = listOf(MediaType.ALL) // 接受任何形式的返回值類型val httpEntity = HttpEntity(request, httpHeaders)val response = restTemplate.postForObject(url, httpEntity, String::class.java)

    Spring Annonation

    • @ConditionalOnMissingBean
    • 注解里的參數的類型如果已經存在一個Bean,那么被此注解修飾的類的方法上面有此注解的方法將不再執行
    • @ConfigurationProperties
    • 將properties或者yml配置直接轉成對象
    • 自定義的配置,對象可以自定義
    • spring為很多模塊提供了對象
    • spring cloud zuul : ZuulProperties

    Spring Integration Test

    • 限定profile和指定profile
    • @ActiveProfiles("integration-mock")
    • @Profile("integration-mock")
    • 使用隨機端口啟動服務,并發送http請求進行集成測試
    • @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    • @Autowired var testRestTemplate: TestRestTemplate? = null

    轉載于:https://www.cnblogs.com/judesheng/p/10622033.html

    總結

    以上是生活随笔為你收集整理的Spring杂记的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。