【Spring注解驱动开发】使用@Autowired@Qualifier@Primary三大注解自动装配组件,你会了吗?

package io.mykit.spring.plugins.register.service;

import io.mykit.spring.plugins.register.dao.PersonDao;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

/**

  • @author binghe

  • @version 1.0.0

  • @description 测试的Service

*/

@Service

public class PersonService {

@Autowired

private PersonDao personDao;

}

  • controller

package io.mykit.spring.plugins.register.controller;

import org.springframework.stereotype.Controller;

/**

  • @author binghe

  • @version 1.0.0

  • @description 测试的controller

*/

@Controller

public class PersonController {

@Autowired

private PersonService personService;

}

可以看到,我们在Service中使用@Autowired注解注入了Dao,在Controller中使用@Autowired注解注入了Service。为了方便测试,我们在PersonService类中生成一个toString()方法,如下所示。

package io.mykit.spring.plugins.register.service;

import io.mykit.spring.plugins.register.dao.PersonDao;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

/**

  • @author binghe

  • @version 1.0.0

  • @description 测试的Service

*/

@Service

public class PersonService {

@Autowired

private PersonDao personDao;

@Override

public String toString() {

return personDao.toString();

}

}

这里,我们在PersonService类的toString()方法中直接调用personDao的toString()方法并返回。为了更好的演示效果,我们在项目的 io.mykit.spring.plugins.register.config 包下创建AutowiredConfig类,如下所示。

package io.mykit.spring.plugins.register.config;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

/**

  • @author binghe

  • @version 1.0.0

  • @description 测试自动装配组件的Config配置类

*/

@Configuration

@ComponentScan(value = {

“io.mykit.spring.plugins.register.dao”,

“io.mykit.spring.plugins.register.service”,

“io.mykit.spring.plugins.register.controller”})

public class AutowiredConfig {

}

接下来,我们来测试一下上面的程序,我们在项目的src/test/java目录下的 io.mykit.spring.test 包下创建AutowiredTest类,如下所示。

package io.mykit.spring.test;

import io.mykit.spring.plugins.register.config.AutowiredConfig;

import io.mykit.spring.plugins.register.service.PersonService;

import org.junit.Test;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值