专业的编程技术博客社区

网站首页 > 博客文章 正文

详解@Bean:你知道几种@Bean使用方式?

baijin 2024-08-15 16:54:35 博客文章 21 ℃ 0 评论

默认方式

@Configuration
public class MyConfig {

    @Bean
    public UserService userService() {
        return new UserService();
    }
}

autowire

  • autowire=Autowire.NO:不会自动注入
  • autowire=Autowire.BY_NAME:根据set方法所对应的属性名查找Bean对象,并进行注入
  • autowire-Autowird.BY_TYPE:根据set方法所对应的属性类型查找Bean对象,并进行注入
@Service
public class RoleService {
}
@Data
public class UserService {

    private RoleService roleService;

    public void printRoleService() {
        System.out.println(roleService);
    }

}
@Configuration
public class MyConfig {

    @Bean(autowire = Autowire.BY_NAME)
    public UserService userService() {
        return new UserService();
    }
}

上述UserService代码可以改成以下代码:

@Data
public class UserService {

    @Resource
    private RoleService roleService;

    public void printRoleService() {
        System.out.println(roleService);
    }
}

MyConfig改成以下代码:

@Configuration
public class MyConfig {

    @Bean
    public UserService userService() {
        return new UserService();
    }
}

autowire虽然功能强大,但使用不灵活。

autowireCandidate

默认值为true,表示可以用来作为依赖注入的候选者;若改为false,则表示不能被用来作为依赖注入的候选者。

public class RoleService {
}
@Data
public class UserService {

    @Autowired
    private RoleService roleService;

    public void printRoleService(){
        System.out.println(roleService);
    }
}
@Configuration
public class MyConfig {

    @Bean
    public UserService userService() {
        return new UserService();
    }

    @Bean(autowireCandidate = false)
    public RoleService roleService() {
        return new RoleService();
    }
}

执行上述代码,调用UserService.printRoleService()则会报错:

No qualifying bean of type 'RoleService' available

修正上述错误有两种方式:

  • 第一种:将MyConfig类中的autowireCandidate的值改为true
  • 第二种:将UserService类中的@Autowired改为@Resource

在@Component定义Bean

@Bean不仅仅只能写在@Configuration类中,还可以在@Component类中定义

@Component
public class MyConfig {

    @Bean
    public String author() {
        return "ijunfu";
    }
}

基于@Bean做扩展

@Bean不仅可以写在方法上,也可以写在类上

之前定义多例Bean:

@Bean
@Scope("prototype")
public RoleService roleService() {
  return new RoleService();
}

现在定义多例Bean:

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Bean
@Scope("prototype")
public @interface MyPrototypeBean {
}
@MyPrototypeBean
public UserService userService() {
  return new UserService();
}

使用@MyPrototypeBean,相当于同时使用了@Bean+@Scope("prototype")。

小结

上述讲述了@Bean的autowire和autowireCandidate两个属性,以及基于@Bean做扩展。相关源码参考ijunfu/My Java - Gitee.com

关注我,不迷路^_^

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表