主要总结一些注解,让自己更容易明白
- @Bean
主要作用于方法上,声明单个bean。一般用于@Configuration注解的类中。
public class WindowsCmd implements ShowCmd {
public String showCmd() {
return "dir";
}
}
@Configuration
public class JavaConfig {
@Bean
ShowCmd winCmd() {
return new WindowsCmd();
}
}
上述java配置bean相当于xml中
<beans>
<bean id="winCmd" class="com.liwang.WindowsCmd"/>
</beans>
我们需要Spring去管理的一个Bean,WindowsCmd 只是一个简单的类,winCmd()中通过new WindowsCmd()返回实例,注入ioc中。
调用
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(JavaConfig.class);
ShowCmd cmd = (ShowCmd) ctx.getBean("cmd");
String s = cmd.showCmd();
System.out.println("s=" + s);
}
}
@Bean 注解,如果不配置名称,则默认使用方法名
-
@Component
主要作用于类上,告知spring创建bean。
@Bean作用在方法上,告知spring这个方法会返回一个对象,该对象要注册为spring应用上下文中的bean,在引用第三方类库中的类时,想要将该类也交给容器管理,可以使用@Bean,方法返回new之后的该类的对象,该对象注册为bean使用。 -
@Qualifier
该注解主要在有多个相同类型Bean中选择我们需要的Bean。可以指定有具体名称的Bean,也可以指定拥有**@Bean 注解**的方法名。因为本身@Bean 在容器中,默认使用方法名作为Bean名。 -
@Primary
该注解主要在多个相同类型的Bean下,指明优先使用有该注解的Bean,与**@Bean 注解或者@Component**一起使用。 -
@ComponentScan
主要用来扫描和 Spring 容器相关的 Bean。 -
@AutoConfigurationPackage
主要用来扫描第三方的 Bean。