Spring-----註解開發和Spring測試單元,spring-----spring

來源:互聯網
上載者:User

Spring-----註解開發和Spring測試單元,spring-----spring
一、註解開發

  • 匯入jar包;spring-aop-xxx.jar
  • 匯入約束:(在官方文檔xsd-configuration.html可找)
    <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"     xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 

     

  • xml中配置掃描開關:

<context:component-scan base-package="com.itheima"/>

  • 1. ioc註解
/* 1. @Component組件,表示要託管這個類,讓spring建立這個類的執行個體。 括弧裡面的us 其實就是id標識符  2. @Component 是通用的註解, 對任何託管的類都可以使用,但是spring為了迎合三層架構,所以對每一層 也給出了具體的註解。          Action  --- @Controller         Service --- @Service         Dao --- @Repository :倉庫,      建議: 如果以後託管三層中的類,請使用具體對應的註解,如果託管的是普通的其他類。@Component  3. 預設產生的執行個體還是單例,如果想做成多例,那麼還得添加一個註解         @Scope("prototype")  4.  @PostConstruct  //初始化執行個體的時候調用        @PreDestroy  //銷毀執行個體之前,調用  5. 如果使用註解託管某一個類,不寫屬性值,那麼預設的id標識符就是類的名字(首字母是小寫) userServiceImpl  6.<!-- 如果想要掃描多個包,就寫一個通用的首碼即可 --><context:component-scan base-package="com.itheima"/> */

DI註解

使用註解來完成依賴注入。 一般註解注入,它針對的點是對象的注入。 spring針對對象的注入,提供了兩個註解  @Resource  和  @Autowired- 常用的註解就兩個 @Resource  &  @Autowired@Resource(name="ud")  根據給定的標記找到對應的類,建立對象,注入進來。@Autowired  自動裝配,會找到對應的實作類別建立對象,注入進來。但是如果存在多個實現,那麼會拋出異常

 

二、Spring測試單元
//spring擴充了junit的運行環境,除了有測試功能之外,還在裡面定義了建立工廠的代碼@RunWith(SpringJUnit4ClassRunner.class)//告訴spring的測試環境,設定檔在哪裡@ContextConfiguration("classpath:applicationContext.xml")public class TestUserService {        //測試類別裡面出現的註解,不用開啟掃描開關。因為這個測試環境裡面,它會解析這個測試類別的註解。       @Autowired    private UserService userService;    @Test    public void testSave(){        userService.save();    } }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.