天天看點

spring基于注解的ioc的demo

本篇是按照上一篇基于xml的代碼來改的

此時已經可以把bean.xml删掉了

先來改造AccountServiceImpl和AccountDaoImpl實作類中的代碼:

首先AccountDaoImpl和AccountServiceImpl實作類中的set都可以删掉了

然後在聲明的變量上面增加Autowired用于自動注入

//AccountDaoImpl中
@Autowired
public QueryRunner runner;
//AccountServiceImpl中
@Autowired
private IAccountDao accountDao;
           

在實作類上表明注解用于建立bean對象

//AccountServiceImpl中
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
	@Autowired
    private IAccountDao accountDao;

    public List<Account> FindAll(){
       return accountDao.FindAll();
    }
}

//AccountDaoImpl中
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    public QueryRunner runner;

    public List<Account> FindAll()  {
        try{
            return runner.query("select * from account", new BeanListHandler<Account>(Account.class));
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }
}
           

然後在建立一個配置類(SpringConfig):

建立一個子配置類(jdbcConfig):

​ (聲明一下他們的作用,SpringConfig是用于整個項目的,即它包含項目中所有的配置類及負責一些總體相關的代碼;而jdbcConfig是用于配置資料庫)

//jdbcConfig
public class jdbcConfig {

    @Value("${jdbc.driver}")
    public String driver;
    @Value("${jdbc.url}")
    public String url;
    @Value("${jdbc.username}")
    public String username;
    @Value("${jdbc.password}")
    public String password;

    @Bean("runner")
    @Scope("prototype")
    public QueryRunner creatQueryRunner(javax.sql.DataSource dataSource){
        return new QueryRunner((javax.sql.DataSource)dataSource);
    }

    @Bean("dataSource")
    public ComboPooledDataSource creatDataSource(){
        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);
        }
    }
}

           

//SpringConfig
@ComponentScan("goulizi")
@Import(jdbcConfig.class)
@PropertySource("classpath:Config.Properties")
public class SpringConfig {
}
           

注意:此時我在jdbcConfig配置類中并沒有将資料庫連接配接的driver、url、username、password給具體寫出來,而我為了不讓他有種定死的感覺,我将它放在了一個properties檔案中,這樣需要求改的時候就直接在這裡面修改了。 在SpringConfig中我使用了PropertySource這個注解用于指定那個properties檔案的位置。

在resources中建立一個properties檔案:

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/test
jdbc.username = root
jdbc.password = 1234
           

注意在jdbcConfig中用Value注解指派時,spring的el語句必須與這個地方的名稱相同。

修改Test測試類:

這裡有兩種方式:

​ 一種是用junit自帶的繼承的main方法,這個方法無法加載spring容器,是以需要我們來給他加載。

@Test
    public void TestFindAll(){
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
        IAccountService as = ac.getBean("accountService", IAccountService.class);
        List<Account> accounts = as.FindAll();
        for (Account account : accounts){
            System.out.println(account);
        }
    }
           

​ 另一種是替換掉這個自帶的main方法,給他換成一個可以加載spring容器的main方法

​ 首先導入spring整合的junit的jar包

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
           

​ 接下來用Runwith注解将main方法換成spring的,并用ContextConfiguration來确定用的是xml還是注解類,并用它标明配置類所在的路徑

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class) 
           

​ 注意:當使用spring5及以上版本時,junit的jar包所添加的依賴必須是4.12版本以上的。

程式運作:

spring基于注解的ioc的demo