(003)spring容器创建bean的其他注解——Component、Controller、Service、Repository

  直接在类上添加@Component注解也可以创建bean,Configuration、Controller、Service、Repository直接继承了Component,只是在应用中语义不同,其他一样。比如Configuration作为创建bean的配置类使用,在其中的方法中用@Bean来创建bean,Controller在应用层,Service和Repository分别在服务层和数据库层

  User.java

package com.edu.spring;

import org.springframework.stereotype.Component;

@Component
public class User {

}
View Code

  App.java

package com.edu.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class App 
{
    public static void main( String[] args )
    {
        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(User.class);
        System.out.println(context.getBean(User.class));
        context.close();
    }
}
View Code

  运行结果如下:

  可以给Component添加属性,指定bean的名字

  User.java

package com.edu.spring;

import org.springframework.stereotype.Component;

@Component("myUser")
public class User {

}
View Code

  App.java

package com.edu.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class App 
{
    public static void main( String[] args )
    {
        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(User.class);
        System.out.println(context.getBean("myUser"));
        context.close();
    }
}
View Code

  运行结果如下:

posted @ 2019-11-02 17:51  雷雨客  阅读(390)  评论(0编辑  收藏  举报