spring小記

註解分類:java

    1.用於建立對象mysql

    2.用於注入數據spring

    3.改變做用範圍sql

    4.生命週期數據庫

1.1mybatis

/**
 * 帳戶的業務層實現類
 *
 * 曾經XML的配置:
 *  <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
 *        scope=""  init-method="" destroy-method="">
 *      <property name=""  value="" | ref=""></property>
 *  </bean>
 *
 * 用於建立對象的
 *      他們的做用就和在XML配置文件中編寫一個<bean>標籤實現的功能是同樣的
 *      @Component:
 *          做用:用於把當前類對象存入spring容器中
 *          屬性:
 *              value:用於指定bean的id。當咱們不寫時,它的默認值是當前類名,且首字母改小寫。
 *      @Controller:通常用在表現層
 *      @Service:通常用在業務層
 *      @Repository:通常用在持久層
 *      以上三個註解他們的做用和屬性與Component是如出一轍。
 *      他們三個是spring框架爲咱們提供明確的三層使用的註解,使咱們的三層對象更加清晰
 *
 *
 * 用於注入數據的
 *      他們的做用就和在xml配置文件中的bean標籤中寫一個<property>標籤的做用是同樣的
 *      @Autowired:
 *          做用:自動按照類型注入。只要容器中有惟一的一個bean對象類型和要注入的變量類型匹配,就能夠注入成功
 *                若是ioc容器中沒有任何bean的類型和要注入的變量類型匹配,則報錯。
 *                若是Ioc容器中有多個類型匹配時:
 *          出現位置:
 *              能夠是變量上,也能夠是方法上
 *          細節:
 *              在使用註解注入時,set方法就不是必須的了。
 *      @Qualifier:
 *          做用:在按照類中注入的基礎之上再按照名稱注入。它在給類成員注入時不能單獨使用,須要配合Autowired一塊兒。可是在給方法參數注入時能夠(見1.3)
 *          屬性:
 *              value:用於指定注入bean的id。
 *      @Resource
 *          做用:直接按照bean的id注入。它能夠獨立使用
 *          屬性:
 *              name:用於指定bean的id。
 *      以上三個注入都只能注入其餘bean類型的數據,而基本類型和String類型沒法使用上述註解實現。
 *      另外,集合類型的注入只能經過XML來實現。
 *
 *      @Value
 *          做用:用於注入基本類型和String類型的數據
 *          屬性:
 *              value:用於指定數據的值。它可使用spring中SpEL(也就是spring的el表達式)
 *                      SpEL的寫法:${表達式}
 *          問題:jsp、mybatis、spring中都有el表達式,如何區分el表達式是誰的?看寫在哪,卸載jsp中就去jsp四大域 
 *               中取值
 *
 * 用於改變做用範圍的
 *      他們的做用就和在bean標籤中使用scope屬性實現的功能是同樣的
 *      @Scope
 *          做用:用於指定bean的做用範圍
 *          屬性:
 *              value:指定範圍的取值。經常使用取值:singleton prototype
 *
 * 和生命週期相關 (瞭解)
 *      他們的做用就和在bean標籤中使用init-method和destroy-methode的做用是同樣的
 *      @PreDestroy
 *          做用:用於指定銷燬方法
 *      @PostConstruct
 *          做用:用於指定初始化方法
 */
@Service("accountService")
//@Scope("prototype")
public class AccountServiceImpl implements IAccountService {

//    @Autowired
//    @Qualifier("accountDao1")
    @Resource(name = "accountDao2")
    private IAccountDao accountDao = null;

    @PostConstruct
    public void  init(){
        System.out.println("初始化方法執行了");
    }

    @PreDestroy
    public void  destroy(){
        System.out.println("銷燬方法執行了");
    }

    public void  saveAccount(){
        accountDao.saveAccount();
    }
}

1.2 框架

/**
 * 該類是一個配置類,它的做用和bean.xml是同樣的
 * spring中的新註解
 * Configuration
 *     做用:指定當前類是一個配置類
 *     細節:當配置類做爲AnnotationConfigApplicationContext對象建立的參數時,該註解能夠不寫。
 * ComponentScan
 *      做用:用於經過註解指定spring在建立容器時要掃描的包
 *      屬性:
 *          value:它和basePackages的做用是同樣的,都是用於指定建立容器時要掃描的包。
 *                 咱們使用此註解就等同於在xml中配置了:
 *                      <context:component-scan base-package="com.itheima"></context:component-scan>
 *  Bean
 *      做用:用於把當前方法的返回值做爲bean對象存入spring的ioc容器中
 *      屬性:
 *          name:用於指定bean的id。當不寫時,默認值是當前方法的名稱
 *      細節:
 *          當咱們使用註解配置方法時,若是方法有參數,spring框架會去容器中查找有沒有可用的bean對象。
 *          查找的方式和Autowired註解的做用是同樣的
 *  Import
 *      做用:用於導入其餘的配置類
 *      屬性:
 *          value:用於指定其餘配置類的字節碼。
 *                  當咱們使用Import的註解以後,有Import註解的類就父配置類,而導入的都是子配置類
 *  PropertySource
 *      做用:用於指定properties文件的位置
 *      屬性:
 *          value:指定文件的名稱和路徑。
 *                  關鍵字:classpath,表示類路徑下
 */
//@Configuration
@ComponentScan("com.itheima")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {


}

何時選擇註解、何時選擇xml配置呢?jsp

    存在於jar包中的,選擇xml配置單元測試

    本身寫的就用註解配置測試

1.3

/**
 * 和spring鏈接數據庫相關的配置類
 */
public class JdbcConfig {

    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    /**
     * 用於建立一個QueryRunner對象
     * @param dataSource
     * @return
     */
    @Bean(name="runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(@Qualifier("ds2") DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 建立數據源對象
     * @return
     */
    @Bean(name="ds2")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Bean(name="ds1")
    public DataSource createDataSource1(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy02");
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

1.4 spring整合junit測試的配置

一、應用程序的入口
	main方法
二、junit單元測試中,沒有main方法也能執行
	junit集成了一個main方法
	該方法就會判斷當前測試類中哪些方法有 @Test註解
	junit就讓有Test註解的方法執行
三、junit不會管咱們是否採用spring框架
	在執行測試方法時,junit根本不知道咱們是否是使用了spring框架
	因此也就不會爲咱們讀取配置文件/配置類建立spring核心容器
四、由以上三點可知
	當測試方法執行時,沒有Ioc容器,就算寫了Autowired註解,也沒法實現注入
/**
 * 使用Junit單元測試:測試咱們的配置
 * Spring整合junit的配置
 *      一、導入spring整合junit的jar(座標)
 *      二、使用Junit提供的一個註解把原有的main方法替換了,替換成spring提供的
 *             @Runwith
 *      三、告知spring的運行器,spring和ioc建立是基於xml仍是註解的,而且說明位置
 *          @ContextConfiguration
 *                  locations:指定xml文件的位置,加上classpath關鍵字,表示在類路徑下
 *                  classes:指定註解類所在地位置
 *
 *   當咱們使用spring 5.x版本的時候,要求junit的jar必須是4.12及以上
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {

    @Autowired
    private IAccountService as = null;


    @Test
    public void testFindAll() {
        //3.執行方法
        List<Account> accounts = as.findAllAccount();
        for(Account account : accounts){
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne() {
        //3.執行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("test anno");
        account.setMoney(12345f);
        //3.執行方法
        as.saveAccount(account);

    }

    @Test
    public void testUpdate() {
        //3.執行方法
        Account account = as.findAccountById(4);
        account.setMoney(23456f);
        as.updateAccount(account);
    }

    @Test
    public void testDelete() {
        //3.執行方法
        as.deleteAccount(4);
    }
}
相關文章
相關標籤/搜索