(一)Spring注解

主要总结一些注解,让自己更容易明白

  1. @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 注解,如果不配置名称,则默认使用方法名

  1. @Component
    主要作用于类上,告知spring创建bean。
    @Bean作用在方法上,告知spring这个方法会返回一个对象,该对象要注册为spring应用上下文中的bean,在引用第三方类库中的类时,想要将该类也交给容器管理,可以使用@Bean,方法返回new之后的该类的对象,该对象注册为bean使用。

  2. @Qualifier
    该注解主要在有多个相同类型Bean中选择我们需要的Bean。可以指定有具体名称的Bean,也可以指定拥有**@Bean 注解**的方法名。因为本身@Bean 在容器中,默认使用方法名作为Bean名。

  3. @Primary
    该注解主要在多个相同类型的Bean下,指明优先使用有该注解的Bean,与**@Bean 注解或者@Component**一起使用。

  4. @ComponentScan
    主要用来扫描和 Spring 容器相关的 Bean。

  5. @AutoConfigurationPackage
    主要用来扫描第三方的 Bean。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值