Spring and Springboot annotations for DI
Spring and Springboot annotations for DI
ancient_wind 发表于2年前
Spring and Springboot annotations for DI
  • 发表于 2年前
  • 阅读 86
  • 收藏 1
  • 点赞 1
  • 评论 1


摘要: Basic annotations for DI

Basic annotaions to describe a bean:

| Annotation | Meaning                                             |
| @Component | generic stereotype for any Spring-managed component |
| @Repository| stereotype for persistence layer                    |
| @Service   | stereotype for service layer                        |
| @Controller| stereotype for presentation layer (spring-mvc)      |

The above annotations can have a optional element: String value.  The value may indicate a suggestion for a logical component name, to be turned into a Spring bean in case of an autodetected component.


Marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities.
If autowire for an interface, it will search for the implementation and inject it.

If there'are multiple implementation, you can use a Map to store the injected implementations.

If you have an interface named Example

public interface Example {

And two implementations:

public class FooExample implements Example {
public class BarExample implements Example {

You can have a map of Example beans injected:

public class ExampleConsumer {
    private final Map<String, Example> examples;
    public ExampleConsumer(Map<String, Example> examples) {
        this.examples = examples;

In this case the map will contain two entries:

  • "foo" -> FooExample instance

  • "bar" -> BarExample instance



Use with @AutowiredThis annotation may be used on a field or parameter as a qualifier for candidate beans when autowiring. It may also be used to annotate other custom annotations that can then in turn be used as qualifiers.


spring @Autowired @Qualifier @Resource


@Autowired: inject by type defaultly;

@Resource: inject by name defaultly.

Spring Injection with @Resource, @Autowired and @Inject



Annotation Package Source
@Resource javax.annotation Java
@Inject javax.inject Java
@Qualifier javax.inject Java
@Autowired org.springframework.bean.factory Spring

For example:

package com.sourceallies.person;


public class Person implements Party { }


In this test I use a ‘@Qualifier’ annotation to point to the qualified name of the ‘Person’ component.

private Party party;
private Party party;
private Party party;

All of these annotations inject the ‘Person’ bean.

To add List of Beans

In this test I inject a list of beans.

private List<Party> parties;
private List<Party> parties;
private List<Party> parties;
  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 2
博文 15
码字总数 7895
评论 (1)
for basic REST: http://spring.io/understanding/REST
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
* 支付类型