zoukankan      html  css  js  c++  java
  • Spring注解之@Component详细解析

    摘自: https://blog.csdn.net/lycyl/article/details/82865009

    @Component是一个元注解,意思是可以注解其他类注解,如@Controller @Service @Repository @Aspect。官方的原话是:带此注解的类看为组件,当使用基于注解的配置和类路径扫描的时候,这些类就会被实例化。其他类级别的注解也可以被认定为是一种特殊类型的组件,比如@Repository @Aspect。所以,@Component可以注解其他类注解。

    源代码:

               @Target({java.lang.annotation.ElementType.TYPE})
               @Retention(RetentionPolicy.RUNTIME)
               @Documented
               public @interface Component {
    
            //这个值可能作为逻辑组件(即类)的名称,在自动扫描的时候转化为spring bean,即相当<bean id="" class="" />中的id
                       public abstract String value();
                }
    

      

    案例:

    a.不指定bean的名称,默认为类名首字母小写university

    @Component
    
    public class University {
    
              to do sthing...
    
    }
    

    获取bean方式:

    ApplicationContext ctx  = new ClassPathXmlApplicationContext("./config/applicationContext.xml");
               University ust = (University) ctx.getBean("university");

    b.指定bean的名称

    @Component("university1")
    
    public class University {
    
              to do sthing...
    
    }
    

    获取bean方式:

    ApplicationContext ctx  = new ClassPathXmlApplicationContext("./config/applicationContext.xml");
               University ust = (University) ctx.getBean("university1");
    

      

      

      

      

  • 相关阅读:
    javaweb(五)——Servlet开发(一)
    JDK1.8改为JDK1.7过程
    javaweb(四)——Http协议(请求头,响应头详解)
    JavaWeb(三)——Tomcat服务器(二)
    JavaWeb(二)——Tomcat服务器(一)
    JavaWeb——JavaWeb开发入门
    java学习之异常总结
    java学习之异常之覆盖
    java学习之异常之格式
    java学习之异常之finally
  • 原文地址:https://www.cnblogs.com/xinruyi/p/11160933.html
Copyright © 2011-2022 走看看