简单说下Spring中@Bean和@Component和XML和JavaConfig配置

首先@Component和@Bean都可以注册Bean。

区别在于:

  • @Component放在类上,表示这个类是组件类,Spring要为这个类创建bean。@Component 和@Repository , @ Controller , @Service一样,局限于自己编写的类中.
  • @Bean放在方法上,对应xml中,方法名就是这个bean的id,返回值就是这个bean的class。@Bean注解告诉Spring这个方法将会返回一个对象,这个对象要注册为Spring应用上下文中的bean。通常方法体中包含了最终产生bean实例的逻辑。使用@Bean可以把第三方库中的类实例交给spring管理。

举例说明:

一个简单的Student类:

@Component
public class Student{
    @Value("jack")
    private String name;
 
    public String getName() {
        return name;
    }
}

一个简单的Teacher类:

public class Teacher{
    @Value("tom")
    private String name;
 
    public String getName() {
        return name;
    }
}

一个简单的Config类:

@Configuration
public class Config{
 
    @Bean
    public Teacher getTeacher()
    {
        return new Teacher();
    }
}

XML中除了component-scan什么都没有。

测试:

public class Test {

    public static void main(String[] args) {
        //如果完全使用了配置类方式去做,我们就只能通过AnnotationConfigApplication上下文来获取容器,通过配置类的class对象加载
//         AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
//         Teacher teacher = (Teacher)context.getBean("getTeacher");//取的getTeacher是方法名
//         System.out.println(teacher.getName());


        ApplicationContext context2=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        Student student = context2.getBean("student",Student.class);
        Teacher Teacher = context2.getBean("seacher",Teacher.class);
        System.out.println(student.getName());
        System.out.println(Teacher.getName());
    }
}
applicationContext.xml
<bean id="student" class="com.cat.test.Student" />
    <bean id="Teacher" class="com.cat.test.Teacher" />

Student注册了bean,Teacher没有自己注册,Config注册了bean,并且引入了Teacher,所以我们也可以获取Teacher的bean,JavaConfig中,@Configuration就包含了@Component,所以也注册了。

JavaConfig和XML是不同的配置方式,如果没有xml,JavaConfig也很好用,@ComponentScan可以用于代替spring的xml配置文件中的<context:component-scan base-package="com.lane.pojo"/>标签。

如果把注释的部分取消注释,则下面的这段通过xml获取容器会失效,会报找不到user这个bean的错,但是XML和JavaConfig可以混合配置,看:https://www.cnblogs.com/bigdataZJ/p/SpringInAction3.html

原文地址:https://www.cnblogs.com/cat520/p/13544004.html