@Component和@Bean的区别
- @Component在类的定义上使用;@Bean在方法上使用,这个方法是获得bean对象的方法。
- @Component是以注解的方式(也就是自动装配)来声明让Spring来创建bean实例;@Bean是基于Java的显示配置来声明让Spring来创建bean实例。
- 正因为@Component是自动装配的方式,所以要使用基于java/xml的显示方式来开启组建扫描;@bean要使用@Configuration来声明某个类是java config类,并且@Bean的方法是在这个java config类上定义的。
demo
@Component
开启组件扫描
创建组件扫描类(基于Java来开启组件扫描)
package com.test.soundsSystem;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class CDPlayerConfig {
}
基于xml开启组建扫描
<context:component-scan base-package="com.test.soundsSystem">
创建bean
package com.test.soundsSystem;
public interface CompactDisc {
void play();
}
package com.test.soundsSystem;
import org.springframework.stereotype.Component;
@Component
public class SgtPeppers implements CompactDisc {
public void play() {
System.out.println("SgtPeppers play");
}
}
@Bean
package com.test.soundsSystem;
public class SgtPeppers implements CompactDisc {
public void play() {
System.out.println("SgtPeppers play");
}
}
@Configuration
public class CDPlayerConfig {
@Bean
public CompactDisc sgtPeppers() {
return new SgtPeppers();
}
}