• spring自动扫描和管理bean


    写在前面:对于spring我真的是小白,可我这个小白发现spring越来越强大了。今天说一下spring自动扫描和管理bean.

    引入spring注解后,有三种方式分别为@service用于注解服务层;@controller用于注解控制层;@responsity用于注解dao;@component用于注解不好分类的类

    这几种注解方式目前而言就是一种规范,实际使用效果没有什么区别。

    下面讲解spring注解的case.

    bean.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    
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
      http://www.springframework.org/schema/context             
      http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
      <context:component-scan base-package="springdao"/> 
      <context:component-scan base-package="serviceImpl"/> <!--如果包比较多,可以多次引入-->
    </beans>


     personDao.java

    @Controller(value="personDao")  @scope("prototype")
    public class personDao {
    private String name;
    private String dep;
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public void Test(){
    System.out.println("hello,spring");
    }
    }
    productCreator.java
    @Component(value="productCreator")
    public class productCreator {
    @Resource
    public personDao pDao=null;
    public productCreator(){
    System.out.println("........正在被创建!");
    }
    public static personDao createPersonDao(){
    return new personDao();
    }
    @PostConstruct //初始化方法,在类被实例化的时候就会被执行
    public void execPdao(){
    pDao.Test();
    }
    }

    springtest.java 

    public static void main(String[] args) {

    ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"beans.xml"});
    personDao pe=(personDao)ctx.getBean("personDao");
    productCreator pea=(productCreator)ctx.getBean("productCreator");
    pe.Test();
    pea.execPdao();
    }

    运行springtest.java得到如下结果:

    ........正在被创建!
    hello,spring
    hello,spring

     

  • 相关阅读:
    skywalking请求头传输协议
    一篇文章带你搞懂SkyWalking调用链追踪框架
    zuihou-admin-cloud很经典的一个微服务开发平台,能够详细的看里面的视频https://www.kancloud.cn/zuihou/zuihou-admin-cloud/1411215
    skywalking权限验证功能
    哔哩哔哩中Openshift红帽培训
    ElasticSearch中文社区视频教程地址
    浅谈一些有趣的区间问题
    浅谈区间最小点覆盖
    洛谷 P1325 雷达安装
    CF12B Correct Solution?
  • 原文地址:https://www.cnblogs.com/php321/p/3394253.html
Copyright © 2020-2023  润新知