Injecting Beans with Annotations in Spring

This article explains how to use Spring annotations such as @Component, @Configuration, @Bean, @Autowired, and @Qualifier to inject beans via XML replacement, constructor injection, setter injection, property injection, List and Map injection, providing code examples and detailed explanations for each method.

Architecture Digest
Architecture Digest
Architecture Digest
Injecting Beans with Annotations in Spring

Injecting Beans with Annotations

When working with Spring, the traditional XML way of defining beans becomes cumbersome for large projects. Spring offers annotation‑based injection, allowing classes to be marked with specific annotations so that the framework automatically scans and registers them in the IoC container.

Background

Typical XML bean definition: <bean id="bean" class="beandemo.Bean"/> Scanning packages via XML:

<context:component-scan base-package="com.company.beandemo"/>

General Annotation Injection

Define a simple bean class: public class MyBean { } Create a configuration class:

// Create a class configuration file
@Configuration
public class MyConfiguration {
    // Register a bean for Spring management
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

In a test, use AnnotationConfigApplicationContext instead of ClassPathXmlApplicationContext to obtain the bean:

ApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
MyBean myBean = context.getBean("myBean", MyBean.class);
System.out.println("myBean = " + myBean);

Constructor Injection

Bean class with constructor injection:

@Component
public class MyBeanConstructor {
    private AnotherBean anotherBeanConstructor;
    @Autowired
    public MyBeanConstructor(AnotherBean anotherBeanConstructor) {
        this.anotherBeanConstructor = anotherBeanConstructor;
    }
    @Override
    public String toString() {
        return "MyBean{" + "anotherBeanConstructor=" + anotherBeanConstructor + '}';
    }
}

Another bean:

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

Configuration for constructor injection:

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

Setter Injection

Bean with a setter method annotated with @Autowired:

@Component
public class MyBeanSet {
    private AnotherBean anotherBeanSet;
    @Autowired
    public void setAnotherBeanSet(AnotherBean anotherBeanSet) {
        this.anotherBeanSet = anotherBeanSet;
    }
    @Override
    public String toString() {
        return "MyBeanSet{" + "anotherBeanSet=" + anotherBeanSet + '}';
    }
}

Property Injection

Injecting a bean directly into a field:

@Component
public class MyBeanProperty {
    @Autowired
    private AnotherBean anotherBeanProperty;
    @Override
    public String toString() {
        return "MyBeanProperty{" + "anotherBeanProperty=" + anotherBeanProperty + '}';
    }
}

List Injection

Bean that receives a List<String> via setter:

@Component
public class MyBeanList {
    private List<String> stringList;
    @Autowired
    public void setStringList(List<String> stringList) {
        this.stringList = stringList;
    }
    public List<String> getStringList() { return stringList; }
}

Configuration providing the list:

@Configuration
@ComponentScan("annoBean.annotationbean")
public class MyConfiguration {
    @Bean
    public List<String> stringList() {
        List<String> stringList = new ArrayList<>();
        stringList.add("List-1");
        stringList.add("List-2");
        return stringList;
    }
    @Bean @Order(34) public String string1() { return "String-1"; }
    @Bean @Order(14) public String string2() { return "String-2"; }
}

Map Injection

Bean that receives a Map<String,Integer> via setter:

@Component
public class MyBeanMap {
    private Map<String,Integer> integerMap;
    public Map<String,Integer> getIntegerMap() { return integerMap; }
    @Autowired
    public void setIntegerMap(Map<String,Integer> integerMap) { this.integerMap = integerMap; }
}

Configuration providing the map and individual beans:

@Bean
public Map<String,Integer> integerMap() {
    Map<String,Integer> map = new HashMap<>();
    map.put("map-1", 1);
    map.put("map-2", 2);
    return map;
}
@Bean public Integer integer1() { return 1; }
@Bean public Integer integer2() { return 2; }

The article concludes that these annotation‑based injection methods can replace XML configuration, offering more concise and flexible ways to manage beans in Spring.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaIoCspringannotationsdependency-injection
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.