Spring实例--注解实现(完全注解形式)

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配置文件,需要解决的问题主要有

  1. 扫描包的问题能不能通过注解来完成?
  2. 数据源和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对象同时加载多个配置类。例如:当有配置类JDBCConfigSpringConfig时,可以这样加载配置 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class, JDBCConfig.class);
当有多个配置类的时候,并且配置类具有总分(父子)关系的时候,可以使用@Import注解。例如:当SpringConfig类是总配置类,JDBCConfig配置类是子配置类,则可使用@Import注解。
在这里插入图片描述
在这里插入图片描述
加载配置直接通过加载总配置即可。 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
当使用@Bean注解注入有多个类型匹配时,便需要@Qualifier注解配合使用。 如下所示:
在这里插入图片描述
关于开发中到底使用什么,这个完全根据自己,比如我喜欢XML配置和注解形式结合使用。

发布了71 篇原创文章 · 获赞 6 · 访问量 5386
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章