草庐IT

Spring注入bean的常用的六种方式

程序猿——小白菜 2024-01-04 原文

一.通过注解注入的一般形式

Bean类

public class TestBean{
}

Configuration类
@Configuration注解去标记了该类,这样标明该类是一个Spring的一个配置类,在加载配置的时候会去加载他。

@Bean的注解,标明这是一个注入Bean的方法,会将下面的返回的Bean注入IOC。

//创建一个class配置文件
@Configuration
public class TestConfiguration{
 //将一个Bean交由Spring进行管理
    @Bean
    public TestBean myBean(){
        return new TestBean();
    }
}

测试类

ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
TestBean testBean = cotext.getBean("testBean",TestBean.class);
System.out.println("testBean = " + testBean);

二.通过构造方法注入Bean

我们在生成一个Bean实例的时候,可以使用Bean的构造方法将Bean实现注入
Bean类

@Component
public class TestBeanConstructor {

 private AnotherBean anotherBeanConstructor;

 @Autowired
 public TeanBeanConstructor(AnotherBean anotherBeanConstructor){
     this.anotherBeanConstructor = anotherBeanConstructor;
 }

 @Override
 public String toString() {
     return "TeanBean{" +
         "anotherBeanConstructor=" + anotherBeanConstructor +
         '}';
 }
}

AnotherBean类

@Component(value="Bean的id,默认为类名小驼峰")
public class AnotherBean {
}

Configuration类

@Configuration
@ComponentScan("com.company.annotationbean")
public class TestConfiguration{
}

注解解释

@AutoWired
自动装配🔧
若是在这里注入的时候指定一个Bean的id就要使用@Qualifier注解。
注释可以在 setter 方法中被用于自动连接 bean,就像 @Autowired 注释,容器,一个属性或者任意命名的可能带有多个参数的方法。
还有不解的地方可以直接百度注解有更详细的解释跟实例

@Component(默认单例模式)
@Component 被称为元注释,它是@Repository、@Service、@Controller、@Configuration的父类,理论上可以使用@Component来注释任何需要Spring自动装配的类。但每个注释都有他们自己的作用,用来区分类的作用,Spring文档上也说明后续版本中可能为@Repository、@Service、@Controller、@Configuration这些注释添加其他功能,所以建议大家还是少使用@Component。
  @Repository注解是任何满足存储库角色或构造型(也称为数据访问对象或DAO)的类的标记。该标记的用途之一是异常的自动翻译,如异常翻译中所述。
  @Service注解一般使用在Service层。
  @Controller注解一般使用在Controller层的类,@RestController继承了@Controller。
  @Configuration注解一般用来配置类,用来项目启动时加载的类。
  
@ComponentScan("")
@ComponentScan注解一般用在Spring项目的核心配置类,或者在Spring Boot项目的启动类里使用。作用就是用来扫描@Component及其子类注释的类,用于Spring容器自动装配。@ComponentScan默认是扫描的路径是同级路径及同级路径的子目录,所以把Spring Boot的启动类放在根目录下,@ComponentScan是可以省略不写的。
主要属性:

  1. value属性、basePackages属性
@AliasFor("basePackages")
String[] value() default {};

@AliasFor("value")
String[] basePackages() default {};

这两个值的作用是一样的,是相互别名的关系。内容是填写要扫描的路径,如果是有一个路径,可以不用写value,有几种写法如下:

@ComponentScan("com.zh.service")

@ComponentScan(value = "com.zh.service")

@ComponentScan(value = {"com.zh.dao", "com.zh.service"})
  1. includeFilters属性、excludeFilters属性
    这两个的作用都是过滤器,excludeFilters的作用是剔除values属性内的个别不需要加载的类,而includeFilters一般是和excludeFilters配合使用,就是被excludeFilters剔除的类里面,还需要其中的几个类,就用includeFilters再加上。

举个例子,假设送了excludeFilters剔除了所有注解是Repository的类,但其中一个Stub开头的类,还要用到,就可以按下面的例子这样写。

ComponentScan.Filter[] includeFilters() default {};

    ComponentScan.Filter[] excludeFilters() default {};

Filter作为过滤器的基本对象

@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface Filter {
    FilterType type() default FilterType.ANNOTATION;

    @AliasFor("classes")
    Class<?>[] value() default {};

    @AliasFor("value")
    Class<?>[] classes() default {};

    String[] pattern() default {};
}

FilterType是过滤器的类型,定义方式有几种

public enum FilterType {
    ANNOTATION,
    ASSIGNABLE_TYPE,
    ASPECTJ,
    REGEX,
    CUSTOM;

    private FilterType() {
    }
}

三.通过set方法注入Bean

我们可以在一个属性的set方法中去将Bean实现注入
Bean类

@Component
public class TestBeanSet {

 private AnotherBean anotherBeanSet;

 @Autowired
 public void setAnotherBeanSet(AnotherBean anotherBeanSet) {
     this.anotherBeanSet = anotherBeanSet;
 }

 @Override
 public String toString() {
     return "TestBeanSet{" +
         "anotherBeanSet=" + anotherBeanSet +
         '}';
 }
}

Configuration类

@Configuration
@ComponentScan("com.company.annotationbean")
public class TestConfiguration{
}

Test类

ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);
TestBean testBean = cotext.getBean("testBean",TestBean.class);
System.out.println("testBean = " + testBean);

四.通过属性去注入Bean

@Component
public class TestBeanProperty {

 @Autowired
 private AnotherBean anotherBeanProperty;

 @Override
 public String toString() {
     return "TestBeanProperty{" +
         "anotherBeanProperty=" + anotherBeanProperty +
         '}';
 }
}

这里可以通过@AutoWired去自动装配它。

五.通过List注入Bean

TestBeanList类

@Component
public class TestBeanList {

 private List<String> stringList;

 @Autowired
 public void setStringList(List<String> stringList) {
     this.stringList = stringList;
 }

 public List<String> getStringList() {
     return stringList;
 }
}

TestConfiguration类()配置类

@Configuration
@ComponentScan("annoBean.annotationbean")
public class TestConfiguration {

    @Bean
    public List<String> stringList(){
       List<String> stringList = new ArrayList<String>();
       stringList.add("List-1");
       stringList.add("List-2");
       return stringList;
    }
}

这里我们将TestBeanList进行了注入,对List中的元素会逐一注入。

下面我们换一种注入List方式
TestConfiguration类

@Bean
//通过该注解设定Bean注入的优先级,不一定连续数字
@Order(34)
public String string1(){
    return "String-1";
}

@Bean
@Order(14)
public String string2(){
    return "String-2";
}

注入与List中泛型一样的类型,会自动去匹配类型,及时这里没有任何List的感觉,只是String的类型,但他会去通过List的Bean的方式去注入。
注意:
第二种方式的优先级高于第一种,当两个都存在的时候,若要强制去使用第一种方式,则要去指定Bean的id即可。

六.通过Map去注入Bean

@Component
public class TestBeanMap {

 private Map<String,Integer> integerMap;

 public Map<String, Integer> getIntegerMap() {
     return integerMap;
 }

 @Autowired
 public void setIntegerMap(Map<String, Integer> integerMap) {
     this.integerMap = integerMap;
 }
}
/**
*第一种注入map方式
*/
@Bean
public Map<String,Integer> integerMap(){
    Map<String,Integer> integerMap = new HashMap<String, Integer>();
    integerMap.put("map-1",1);
    integerMap.put("map-2",2);
    return integerMap;
}
/**
*第二种注入map方式
*/
@Bean
public Integer integer1(){
    return 1;
}

@Bean
public Integer integer2(){
    return 2;
}

这里跟List一样,第二种优先级大于第一种

有关Spring注入bean的常用的六种方式的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. ruby - 如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串? - 2

    我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123

  3. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  4. ruby-on-rails - 带 Spring 锁的 Rails 4 控制台 - 2

    我正在使用Ruby2.1.1和Rails4.1.0.rc1。当执行railsc时,它被锁定了。使用Ctrl-C停止,我得到以下错误日志:~/.rvm/gems/ruby-2.1.1/gems/spring-1.1.2/lib/spring/client/run.rb:47:in`gets':Interruptfrom~/.rvm/gems/ruby-2.1.1/gems/spring-1.1.2/lib/spring/client/run.rb:47:in`verify_server_version'from~/.rvm/gems/ruby-2.1.1/gems/spring-1.1.

  5. ruby-on-rails - 正确的 Rails 2.1 做事方式 - 2

    question的一些答案关于redirect_to让我想到了其他一些问题。基本上,我正在使用Rails2.1编写博客应用程序。我一直在尝试自己完成大部分工作(因为我对Rails有所了解),但在需要时会引用Internet上的教程和引用资料。我设法让一个简单的博客正常运行,然后我尝试添加评论。靠我自己,我设法让它进入了可以从script/console添加评论的阶段,但我无法让表单正常工作。我遵循的其中一个教程建议在帖子Controller中创建一个“评论”操作,以添加评论。我的问题是:这是“标准”方式吗?我的另一个问题的答案之一似乎暗示应该有一个CommentsController参

  6. 【鸿蒙应用开发系列】- 获取系统设备信息以及版本API兼容调用方式 - 2

    在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList​()Obt

  7. spring.profiles.active和spring.profiles.include的使用及区别说明 - 2

    转自:spring.profiles.active和spring.profiles.include的使用及区别说明下文笔者讲述spring.profiles.active和spring.profiles.include的区别简介说明,如下所示我们都知道,在日常开发中,开发|测试|生产环境都拥有不同的配置信息如:jdbc地址、ip、端口等此时为了避免每次都修改全部信息,我们则可以采用以上的属性处理此类异常spring.profiles.active属性例:配置文件,可使用以下方式定义application-${profile}.properties开发环境配置文件:application-dev

  8. ruby - 鸭子输入字符串、符号和数组的优雅方式? - 2

    这是针对我无法破坏的现有公共(public)API,但我确实希望对其进行扩展。目前,该方法采用字符串或符号或任何其他在作为第一个参数传递给send时有意义的内容我想添加发送字符串、符号等列表的功能。我可以只使用is_a吗?数组,但还有其他发送列表的方法,这不是很像ruby​​。我将调用列表中的map,所以第一个倾向是使用respond_to?:map。但是字符串也会响应:map,所以这行不通。 最佳答案 如何将它们全部视为数组?String的行为与仅包含String的Array相同:deffoo(obj,arg)[*arg].eac

  9. ruby - 这个 ruby​​ 注入(inject)魔术是如何工作的? - 2

    我今天看到了一个ruby​​代码片段。[1,2,3,4,5,6,7].inject(:+)=>28[1,2,3,4,5,6,7].inject(:*)=>5040这里的注入(inject)和之前看到的完全不一样,比如[1,2,3,4,5,6,7].inject{|sum,x|sum+x}请解释一下它是如何工作的? 最佳答案 没有魔法,符号(方法)只是可能的参数之一。这是来自文档:#enum.inject(initial,sym)=>obj#enum.inject(sym)=>obj#enum.inject(initial){|mem

  10. ruby - 如何以编程方式删除实例上的 "singleton information"以使其编码(marshal)? - 2

    我创建了一个由于“在运行时执行的单例元类定义”而无法编码的对象(这段代码的描述是否正确?)。这是通过以下代码执行的:#defineclassXthatmyusesingletonclassmetaprogrammingfeatures#throughcallofmethod:break_marshalling!classXdefbreak_marshalling!meta_class=class我该怎么做才能使对象编码正确?是否可以从对象instance_of_x的classX中“移除”单例组件?我真的需要一个建议,因为我们的一些对象需要通过Marshal.dump序列化机制进行缓存。

随机推荐