Spring5框架 IOC 注解练习

IOC(控制反转) 、DI(依赖注入)这两个概念
@Repository 存储层
@Service 服务层
@Controller 控制层
@Component 与上三个一致
@Autowired 声明类型
@Qualifier 声明名称与Autowired 并列使用
@Resource 既可以使用类型有可以使用名称
--实例一
  use-default-filters="false":表示不适用默认的filter,自己配置
  context:include-filter:只扫描那些 注解为:Controller 别的不扫描

  <context:component-scan base-package="com.atguigu" use-default-filters="false">
      <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  </context:component-scan>
实例2
  下面的配置
 context:exclude-filter:不扫描那些 注解为:Controller 扫描

  <context:component-scan base-package="com.atguigu" >
      <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  </context:component-scan>

    <!--开启组件扫描
 1 如果扫描多个包,多个包使用逗号隔开
 2 扫描包上层目录
-->
    <context:component-scan base-package="com.atguigu"></context:component-scan>

需要的jar包:

1.dao层创建接口以及dao层接口的实现类

public interface ChaoDao {
    public void add();
}
@Repository  //dao层使用的注解 //如果没有value 那么默认就是类的首字母小写:chaoService
public class ChaoDaoImpl implements ChaoDao{
    @Override
    public void add() {
        System.out.println("ChaoDaoImpl.add");
    }
}

2.service层

@Service//如果没有value 那么默认就是类的首字母小写:chaoService
public class ChaoService {
    ChaoDao chaoDao =new ChaoDaoImpl();
    public void say(){
        System.out.println("ChaoService.say.");
        chaoDao.add();
    }
}

3.全注解开发类

/*@Configuration //作为配置类,替代 xml 配置文件
@ComponentScan(basePackages = {"com.atguigu"}) 扫描路径
*/
@Configuration
@ComponentScan(basePackages = {"com.atguigu"})
public class SpingConfig {
}

4测试

public class ChaoTest {
    @Test //完全使用注解开发
    public void test(){
        //通过配置类 SpingConfig 获取注解扫描路径
        ApplicationContext context=new AnnotationConfigApplicationContext(SpingConfig.class);
        //获取实例对象
        ChaoService chaoService = context.getBean("chaoService", ChaoService.class);
        //执行方法
        chaoService.say();
    }
    @Test //使用xml 配置文件注解开发,zhujiebean.xml文件存放于src目录下
    public void test1(){
        ApplicationContext context=new ClassPathXmlApplicationContext("zhujiebean.xml");
        ChaoService chaoService = context.getBean("chaoService", ChaoService.class);
        chaoService.say();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值