基于注解的 IOC 配置

常用注解

1.用于创建对象的

@Component相当于:<bean id="" class="">

作用:

把资源让 spring 来管理。相当于在 xml 中配置一个 bean。

属性:

value:指定 bean 的 id。如果不指定 value 属性,默认 bean 的 id 是当前类的类名。首字母小写。

@Controller @Service @Respository

他们三个注解都是针对一个的衍生注解,他们的作用及属性都是一模一样的。

他们只不过是提供了更加明确的语义化。

@Controller :一般用于表现层的注解。

@Service :一般用于业务层的注解。

@Repository :一般用于持久层的注解。

细节:如果注解中有且只有一个属性 要赋值时是 ,且名称是 value ,value 在赋值是可以不写。

2.用于注入数据的

@Autowired

相当于:<property name="" ref="">

<property name="" value="">

作用:

自动按照类型注入。当使用注解注入属性时,set方法可以省略。它只能注入其他 bean 类型。当有多个类型匹配时,单用它会报错。

出现位置:变量或方法上

@Qualifier

作用:

在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和@Autowire 一起使用;但是给方法参数注入时,可以独立使用。

属性:

value:指定 bean 的 id。

@Resource

作用:

直接按照 Bean 的 id 注入。它也只能注入其他 bean 类型。

属性:

name:指定 bean 的 id。

以上三个注解均不可用于基本类型和String类型,另外集合类型只可以用xml实现注入

@Value

作用:

注入基本数据类型和 String 类型数据的

属性:

value:用于指定值。它可以使用spring中的SpEL

SpEL的写法:${表达式}

3.用于改变作用范围的

@Scope

作用:

指定 bean 的作用范围。

属性:

value:指定范围的值。

取值:singleton prototype request session globalsession

4.和生命周期相关的

相当于:<bean id="" class="" init-method="" destroy-method="" />

@PostConstruct

作用:

用于指定初始化方法。

@PreDestroy

作用:

用于指定销毁方法。

 

5.其他注解

@Configuration

作用:

用于指定当前类是一个 spring 配置类,当创建容器时会从该类上加载注解。获取容器时需要使用

AnnotationApplicationContext(有@Configuration 注解的类.class)。

属性:

value:用于指定配置类的字节码

@ComponentScan

作用:

用于指定 spring 在初始化容器时要扫描的包。作用和在 spring 的 xml 配置文件中的:

<context:component-scan base-package="com.itheima"/>是一样的。

属性:

basePackages:用于指定要扫描的包。和该注解中的 value 属性作用一样。

@Bean

作用:

该注解只能写在方法上,表明使用此方法创建一个对象,并且放入 spring 容器。

属性:

name:给当前@Bean 注解方法创建的对象指定一个名称(即 bean 的 id)。

@PropertySource

作用:

于加载.properties 文件中的配置。例如我们配置数据源时,可以把连接数据库的信息写到

properties 配置文件中,就可以使用此注解指定 properties 配置文件的位置。

属性:

value[]:用于指定 properties 文件位置。如果是在类路径下,需要写上 classpath:

@Import

作用:

用于导入其他配置类,在引入其他配置类时,可以不用再写@Configuration 注解。当然,写上也没问题。

属性:

value[]:用于指定其他配置类的字节码。

6.Spring整合Junit

Spring整合Junit的配置:

  1. 导入spring整的junit坐标
  2. 使用@RunWith 注解替换原有运行器
  3. 使用@ContextConfiguration 指定 spring 配置文件的位置(classes制定注解类所在位置,locations指定xml文件所在位置,加上classpath表示类路径下)
  4. 使用@Autowired 给测试类中的变量注入数据

实例代码:

项目依赖

 <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>
        <dependency>

            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    </dependencies>

持久层接口以及实现类

public interface IAccountDao {
    /**
     * 查询所有
     *
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     *
     * @return id
     */
    Account findById(Integer id);

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

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

    /**
     * 删除
     *
     * @param id
     */
    void deleteAccount(Integer id);
}
@Repository("ac")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private QueryRunner runner;

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

    public Account findById(Integer id) {
        try {
            return runner.query("select * from account_two where id =?", new BeanHandler<Account>(Account.class), id);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

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

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

    public void deleteAccount(Integer id) {
        try {
            runner.update("delete from account where id =?", id);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }
}

Service层接口以及实现类

public interface IAccountService {
    /**
     * 查询所有
     *
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     *
     * @return id
     */
    Account findById(Integer id);

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

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

    /**
     * 删除
     *
     * @param id
     */
    void deleteAccount(Integer id);
}
@Service("accountService")
public class AccountServiceImp implements IAccountService {
    @Resource(description = "ac")
    private IAccountDao accountDao;

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

    public Account findById(Integer id) {
        return accountDao.findById(id);
    }

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

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

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

配置类

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("ds") DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name="ds")
    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);
        }
    }
}
@Configuration
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
@ComponentScan("com.tiger")
public class SpringConfiguration {
}

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
    @Autowired
    private IAccountService as;

    @Test
    public void testFindAll() {
        List<Account> allAccount = as.findAllAccount();
        for (Account account : allAccount) {
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne() {

        Account byId = as.findById(1);
        Account byId2 = as.findById(2);
        System.out.println(byId);
    }

    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("zs");
        account.setId(55);
        account.setMoney(1000000);
        as.saveAccount(account);
    }

    @Test
    public void testUpdate() {

    }

    @Test
    public void testDelete() {
        as.deleteAccount(1);
    }
}

工程结构图

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值