Spring實例–註解實現一文中,雖然用了很多註解去完成Ioc等操作,但是仍然需要XML去配置掃描的包等等。接下來就說說怎麼完全的捨棄XML配值文件吧。
Spring實例–註解實現的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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--掃描包-->
<context:component-scan base-package="com.liang"></context:component-scan>
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mySpring?serverTimezone=UTC"></property>
<property name="user" value="root"></property>
<property name="password" value="liang"></property>
</bean>
</beans>
從配置文件中可以看出,要不使用XML配置文件,需要解決的問題主要有
- 掃描包的問題能不能通過註解來完成?
- 數據源和QueryRunner配置能不能通過註解來完成?
解決以上兩個問題,用以前的註解肯定不能夠完成,還是先看看其他註解吧。
註解說明
註解 | 功能 |
---|---|
@Configuration | 用於指定當前類是Spring配置類,當配置類作爲AnnotationConfigApplicationContext對象創建的參數時,該註解可以不寫。value屬性: |
@ComponentScan | 指定Spring在創建容器時需要掃描的包。 basePackages(value)屬性:指定需要掃描的包 |
@Bean | 用於類中的方法上面,表示使用此方法創建一個對象,並存入Spring容器中。name屬性:給創建的對象指定一個名稱 |
@PropertySource | 用於加載.properties文件中的配置。value[]屬性:用於指定properties文件位置,類路徑下需加上classpath: |
@Import | 用於導入其他配置類,在引入其他配置類時,可以不用@Configuration註解 |
編寫用戶實體類
public class Account {
private int id;
private String name;
private float money;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
編寫持久層接口及實現類
/**
* 賬戶的持久層接口
*/
public interface AccountDao {
/**
* 查詢所有賬戶
* @return
*/
public List<Account> findAllAccount();
/**
*通過賬戶id查詢賬戶
* @param accountId
* @return
*/
public Account findAccountById(int accountId);
/**
* 保存賬戶
* @param account
*/
void saveAccount(Account account);
/**
* 更新賬戶信息
*/
public void updateAccount(Account account);
/**
* 通過賬戶id刪除賬戶
* @param accountId
*/
public void deleteAccount(int accountId);
}
/**
* 賬戶持久層接口的實現類
*/
@Repository(value = "accountDao")
public class AccountDaoImpl implements AccountDao {
//提供對sql語句操作的API
@Autowired
private QueryRunner queryRunner;
public List<Account> findAllAccount() {
try {
return queryRunner.query("select *from account",new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Account findAccountById(int accountId) {
try {
return queryRunner.query("select *from account where id = ?", new BeanHandler<Account>(Account.class), accountId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void saveAccount(Account account ) {
try {
queryRunner.update("insert into account(name,money) value(?,?)",account.getName(),account.getMoney());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void updateAccount(Account account) {
try {
queryRunner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void deleteAccount(int accountId) {
try {
queryRunner.update("delete from account where id=?",accountId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
編寫業務層接口及實現類
/**
* 賬戶業務層接口
*/
public interface AccountService {
/**
* 查詢所有賬戶
* @return
*/
public List<Account> findAllAccount();
/**
*通過賬戶id查詢賬戶
* @param accountId
* @return
*/
public Account findAccountById(int accountId);
/**
* 保存賬戶
*/
void saveAccount(Account account);
/**
* 更新賬戶信息
*/
public void updateAccount(Account account);
/**
* 通過賬戶id刪除賬戶
* @param accountId
*/
public void deleteAccount(int accountId);
}
/**
* 賬戶的業務層實現類
*/
@Service(value = "accountService")
public class AccountServiceImpl implements AccountService {
@Resource(name = "accountDao")
private AccountDao accountDao;
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
public Account findAccountById(int accountId) {
return accountDao.findAccountById(accountId);
}
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
public void deleteAccount(int accountId) {
accountDao.deleteAccount(accountId);
}
}
編寫配置類
@Configuration
@ComponentScan(basePackages = {"com.liang"})
@PropertySource(value = "classpath:jdbc.properties")
public class SpringConfig {
@Value(value = "${driver}")
private String driver;
@Value(value = "${url}")
private String url;
@Value(value = "${user}")
private String user;
@Value(value = "${password}")
private String password;
@Bean(value = "queryRunner")
@Scope(value = "prototype")
public QueryRunner createQueryRunner(DataSource dataSource)
{
return new QueryRunner(dataSource);
}
@Bean(value = "dataSource")
public DataSource createDataSource()
{
try{
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setDriverClass(driver);
comboPooledDataSource.setJdbcUrl(url);
comboPooledDataSource.setUser(user);
comboPooledDataSource.setPassword(password);
return comboPooledDataSource;
}catch (Exception e) {
throw new RuntimeException("數據庫配置錯誤");
}
}
}
數據庫連接配置文件
編寫測試類
public class SpringTest {
private AccountService accountService;
@Before
public void init()
{
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
accountService = (AccountService)applicationContext.getBean("accountService");
System.out.println(accountService);
}
@Test
public void testFindAllAccount()
{
List<Account> accounts = accountService.findAllAccount();
for (Account account:accounts)
{
System.out.println(account);
}
}
@Test
public void testFindAccountById()
{
Account account = accountService.findAccountById(1);
System.out.println(account);
}
@Test
public void testSaveAccount()
{
Account account = new Account();
account.setName("灰太狼");
account.setMoney(0.01f);
accountService.saveAccount(account);
}
@Test
public void testUpdateAccount()
{
Account account = accountService.findAccountById(4);
account.setMoney(0.001f);
accountService.updateAccount(account);
}
@Test
public void testDeleteAccount()
{
accountService.deleteAccount(4);
}
}
當有多個配置類的時候。可以通過AnnotationConfigApplicationContext對象同時加載多個配置類。例如:當有配置類JDBCConfig和SpringConfig時,可以這樣加載配置 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class, JDBCConfig.class);。
當有多個配置類的時候,並且配置類具有總分(父子)關係的時候,可以使用@Import註解。例如:當SpringConfig類是總配置類,JDBCConfig配置類是子配置類,則可使用@Import註解。
加載配置直接通過加載總配置即可。 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);。
當使用@Bean註解注入有多個類型匹配時,便需要@Qualifier註解配合使用。 如下所示:
關於開發中到底使用什麼,這個完全根據自己,比如我喜歡XML配置和註解形式結合使用。