Spring之注解配置IoC

注解配置

定义配置

  • @Configuration:指定当前类是一个配置类
  • @ComponentScan:用于通过注解指定Spring在创建容器时要扫描的包
    @ComponentScan(basePackages="")@ComponentScan(value="")指定包名
  • @Bean:用于把当前方法的返回值作为bean对象存入Spring的IoC容器中
    @Bean(name="")指定bean的id,默认值是当前方法的名称。
  • @Import:导入其他的配置类。
    @Import(Class对象)指定要导入的配置类(通常是被AnnotationConfigApplicationContext指定的主配置类关联其他的子配置类)

通过注解配置则获取ApplicationContext的时候需要通过实现类AnnotationConfigApplicationContext(Class对象)获取。

Spring只会扫描配置类下的@Bean

用于创建对象

  • @Component:将当前的类对象存入spring容器中

id可以通过@Component(value = "")修改,如果不设置默认id是类名的首字母变小写。

在spring配置文件中配置扫描包范围:

<?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">

    <!-- 告知spring在创建容器时要扫描的包 -->
    <context:component-scan base-package="com.rhett"></context:component-scan>
</beans>
  • @Controller:一般用于表现层
  • @Service:一般用于业务层
  • @Repository:一般用于持久层

作用和属性和Component一样,只为区分三层的概念。

用于注入数据

  • @Autowired:自动按照类型注入,只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功。

此时set方法不是必须的

如果容器中有多个类型可以匹配的bean对象,则会把要注入的变量的名称作为id查找是否有的对应的bean对象。

  • @Qualifier:再按照类中注入的基础之上再按照名称注入。它在给类成员注入时不能单独使用(需要配合@Autowired),但是在给方法参数注入时可以。

@Qualifier(value="")可以指定要装配的bean在容器中的id。

  • @Primary:可以指定当有多个类型可以匹配的bean对象优先注入的对象。

  • @Resource:直接把字段名当作bean的id识别注入,可以单独使用。

  • @Resource(name=""):指定一个bean的id,在这个bean中查找属性名和当前字段名吻合的对象注入。

以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现。

集合类型的注入只能通过XML实现。

  • @Value():用于注入基本类型和String类型。value可以使用Spring的SpEL表达式:${表达式}

  • @PropertySource:用于指定properties文件的位置
    @PropertySource(value="")指定文件名称和路径,通过前缀classpath:指定类路径下的。

用于改变作用范围

  • @Scope:和bean标签中的scope属性的作用是一样的。

@Scope(value="")指定bean的作用范围。

和生命周期相关

  • @PreDestroy:指定销毁前调用的方法

  • @PostConstruct:指定构造后调用的方法

这两个注解都是写在方法上。

条件装配Bean

有时候某些客观的因素会使一些Bean无法进行初始化,例如,在数据库连接池的配置中漏掉一些配置会造成数据源不能连接上。在这样的情况下,可能不希望IoC去装配数据源,Spring4提供了新注解@Conditional,它的作用是按照一定的条件进行判断,满足条件给容器注册bean。它还需要配合另外一个接口Condition来完成对应的功能:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {

    /**
     * All {@link Condition Conditions} that must {@linkplain Condition#matches match}
     * in order for the component to be registered.
     */
    Class<? extends Condition>[] value();

}
@FunctionalInterface
public interface Condition {

    /**
     * Determine if the condition matches.
     * @param context the condition context
     * @param metadata metadata of the {@link org.springframework.core.type.AnnotationMetadata class}
     * or {@link org.springframework.core.type.MethodMetadata method} being checked
     * @return {@code true} if the condition matches and the component can be registered,
     * or {@code false} to veto the annotated component's registration
     */
    boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);

}

Conditional根据Condition中的match方法,返回true则注入bean,false则不注入。

基于xml配置的Spring IoC实例

实体类

/**
 * 账户的实体类
 */
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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 IAccountDao {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 保存
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 删除
     * @param accountId
     */
    void deleteAccount(Integer accountId);
}
/**
 * 账户的持久层实现类
 */
public class AccountDaoImpl implements IAccountDao {

    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    public List<Account> findAllAccount() {
        try {
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Account findAccountById(Integer accountId) {
        try {
            return runner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),accountId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void saveAccount(Account account) {
        try {
            runner.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateAccount(Account account) {
        try {
            runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void deleteAccount(Integer accountId) {
        try {
            runner.update("delete from account where id=?",accountId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

业务层

/**
 * 账户的业务层接口
 */
public interface IAccountService {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 保存
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 删除
     * @param accountId
     */
    void deleteAccount(Integer accountId);
}
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

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

    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

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

    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    public void deleteAccount(Integer accountId) {
        accountDao.deleteAccount(accountId);
    }
}

Spring配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 业务层对象 -->
    <bean id="accountService" class="com.rhett.service.impl.AccountServiceImpl">
        <!--注入Dao-->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!-- 配置Dao对象 -->
    <bean id="accountDao" class="com.rhett.dao.impl.AccountDaoImpl">
        <property name="runner" ref="runner"></property>
    </bean>

    <bean id="runner" 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://192.168.91.1:3306/learnSpring"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
</beans>

测试类

/**
 * 使用Junit单元测试,测试我们的配置
 */
public class AccountServiceTest {

    ApplicationContext ac;
    IAccountService as;

    @Before
    public void init(){
        //1.获取容器
        ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        as = ac.getBean("accountService",IAccountService.class);
    }

    @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");
        account.setMoney(12345f);
        as.saveAccount(account);
    }
    @Test
    public void testUpdate() {
        Account account = new Account();
        account.setMoney(23456f);
        account.setId(4);
        as.updateAccount(account);
    }
    @Test
    public void testDelete() {
        as.deleteAccount(5);
    }
}

基于注解配置的Spring IoC实例

实体类不变。

持久层

/**
 * 账户的持久层实现类
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private QueryRunner runner;

    //不变...
}

加入@Repository@Autowired

业务层

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

    //不变...
}

加入@Service@Autowired

编写配置类

/**
 * 该类是一个配置类,它的作用和bean.xml是一样的
 */
@Configuration
@ComponentScan("com.rhett")
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
    @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(DataSource dataSource){
        return new QueryRunner(dataSource);
    }
    @Bean(name="dataSource")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        return null;
    }
}

properties文件:

jdbc.driver = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://192.168.91.1:3306/learnSpring
jdbc.username = root
jdbc.password = 123456

测试类

public class AccountServiceTest {

    ApplicationContext ac;
    IAccountService as;

    @Before
    public void init(){
        //1.获取容器
        ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //2.得到业务层对象
        as = ac.getBean("accountService",IAccountService.class);
    }
    //不变...
}

Spring整合JUnit测试

导入maven依赖:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.3.RELEASE</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

使用JUnit提供的一个注解把原有的main方法替换称Spring提供的,它在运行时会自动创建Spring容器:

@RunWith(SpringJUnit4ClassRunner.class)

告知Spring的运行器,Spring的IoC创建是基于xml还是注解的,并且说明位置:

  • @ContextConfiguration(locations={}):指定xml文件的位置
  • @ContextConfiguration(classes={}):指定配置类所在的位置

修改之后的测试类:

import java.util.List;

/**
 * 使用Junit单元测试,测试我们的配置
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {

    @Autowired
    IAccountService as;

    //不变...
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/spring%e4%b9%8b%e6%b3%a8%e8%a7%a3%e9%85%8d%e7%bd%aeioc/

(0)
彭晨涛彭晨涛管理者
上一篇 2020年2月24日 20:55
下一篇 2020年2月25日 01:21

相关推荐

发表回复

登录后才能评论