I would recommend to look into plain Spring configuration first to get a feel of how fundamental things (like injection) work. If you manage to get a hang of it in Spring, the process will be very similar in Spring MVC/Spring Boot/etc. Personally, I find it very frustrating trying to juggle multiple concepts (view resolvers, different configuration files, views, repositories, multiple annotations, multiple ways of configuration, etc.) at once, so I tend to start from the simplest concepts and build my way up. Once you are comfortable with how injection works, you can easily apply this knowledge elsewhere.

As for java config and annotations, they do allow for much quicker and cleaner development. XML is quite verbose, hard to maintain and is very prone to errors, in part because IDEs are generally more helpful when working with java based configuration. Perhaps that is why you read that XML is being deprecated. I would recommend to go for java/auto configuration rather than XML one, unless you really need to (or are interested in it).

Now onto how to do it. A complete (but minimal) working Spring example:

/* Bean definition

@Component tells Spring that this is a bean. There are a few similar annotations.
It will be discovered during the component scan, as it has @Component annotation */

package main.java.org.example;
import org.springframework.stereotype.Component;

@Component 
public class Greeting {
    private String greeting = "Hello";

    public String getGreeting() {
        return this.greeting;
    }

    public void setGreeting(String greeting) {
        this.greeting = greeting;
    }
}


/* Another bean definition.
It has another bean as a dependency, which we inject with a setter. */

package main.java.org.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class GreetingCollector {
    private Greeting greeting;

    /* This is how you do setter injection */
    @Autowired
    public void setGreeting(Greeting greeting) {
        this.greeting = greeting;
    }

    public String getGreeting() {
        return greeting.getGreeting();
    }
}


/* This is a minimal config class. 
@ComponentScan instructs to look for classes that are 
annotated with @Component annotation (in other words, beans) */

package main.java.org.example;    
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan
@Configuration
public class Config {}

If you want to do it explicitly:

package main.java.org.example;  
import main.java.org.example.GreetingCollector;
import main.java.org.example.Greeting;  
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {
    @Bean
    public Greeting greeting() {
        return new Greeting();
    }

    @Bean
    public GreetingCollector greetingCollector(Greeting greeting) {
        return new GreetingCollector(greeting);
    }
}

And if you want to run it just to see how it works:

import main.java.org.example.Config;
import main.java.org.example.GreetingCollector;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AppContext {
    public static void main(String args[]) {
        System.out.println("Configuring application context...");
        ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        GreetingCollector collector = (GreetingCollector) context.getBean("greetingCollector");
        System.out.println(collector.getGreeting());
    }
}

Naturally, Spring web application would be a bit different, but the basic injection idea is the same. First, you need to declare beans (either by using @Bean, @Component or any other annotation: see here and here for differences). You annotate either a setter or constructor (or even a field) with @Autowired, specify parameters (which do not necessarily need to be concrete classes - interfaces, abstract classes are fine, too), assign them to appropriate fields. Create a config class which takes cares of bean instantiation. You do not need to have your components in the same folder as config classes, as you can always specify where to look for components. Finally, if you want a more fine grained control, you can always declare beans explicitly in configuration class (so called JavaConfig, whereas @ComponentScan based config might sometimes be called autoconfig). This should be enough to get you started and give you vocabulary to search for more advanced stuff.

And of course, with Spring Boot everything is even more abstracted away/quicker.

Answer from cegas on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com › spring › setter_based_dependency_injection.htm
Spring - Setter-based Dependency Injection
package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); TextEditor te = (TextEditor) context.getBean("textEditor"); te.spellCheck(); } } Following is the configuration file Beans.xml which has configuration for the setter-based injection −
🌐
Java Guides
javaguides.net › 2023 › 01 › spring-boot-setter-injection-example.html
Spring Boot Setter Injection Example
April 4, 2023 - We have annotated SMSService class ... and manages its life cycle. In setter injection, Spring will find the @Autowired annotation and call the setter to inject the dependency....
Discussions

xml - How do I use setter injection with java configuration in Spring? - Stack Overflow
You would find many example implemented using XML as XML was widely used in earlier days of Spring. Now with the advent of Spring 4 and Spring Boot. Most of the developers don't use XML on a large scale. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Results of the October 2025 Community Asks Sprint: copy button for code... Chat room owners can now establish room guidelines ... 0 Setter injection ... More on stackoverflow.com
🌐 stackoverflow.com
When to use Constructor Injection vs. Setter Injection
Never use setter injection. At least, never use it as much as possible. Reason being that it encourages mutability. You should always aim for complete immutability. More on reddit.com
🌐 r/SpringBoot
11
7
March 18, 2023
dependency injection - Setter DI vs. Constructor DI in Spring? - Stack Overflow
Spring has two two types of DI (Dependency Injection): setter DI and construction DI. Constructor-based DI fixes the order in which the dependencies need to be injected. Setter based DI does not of... More on stackoverflow.com
🌐 stackoverflow.com
Spring Dependency Injection Patterns - The Good, The Bad, and The Ugly
As an added bonus, since final fields can be initialised in the constructor, our dependencies can be immutable - as they should be! Amen to that. I find stateless/immutable services to be a lot easier to deal with. Why worry about object lifetimes when you can just make every service a singleton? More on reddit.com
🌐 r/java
55
35
February 14, 2018
🌐
amitph
amitph.com › home › spring › spring setter dependency injection example
Spring Setter Dependency Injection Example | amitph
November 22, 2024 - Line #40: Setter of DogsController is called. The DogsService instance (created in line #37) is injected. The log shows that the objects get created first and then the dependency is injected. Very similar to Setter Injection Spring also supports Field Injection.
🌐
GeeksforGeeks
geeksforgeeks.org › spring-dependency-injection-by-setter-method
Spring - Dependency Injection by Setter Method - GeeksforGeeks
In Setter-Based Dependency Injection, dependencies are provided using setter methods. First, the Spring IoC container creates the object using a no-argument constructor, and then it calls the setter methods to set the required dependencies. Example: This example demonstrates how to use Setter-Based Dependency Injection (DI) in Spring, where dependencies are injected using setter methods.
Published   March 3, 2025
Top answer
1 of 2
8

I would recommend to look into plain Spring configuration first to get a feel of how fundamental things (like injection) work. If you manage to get a hang of it in Spring, the process will be very similar in Spring MVC/Spring Boot/etc. Personally, I find it very frustrating trying to juggle multiple concepts (view resolvers, different configuration files, views, repositories, multiple annotations, multiple ways of configuration, etc.) at once, so I tend to start from the simplest concepts and build my way up. Once you are comfortable with how injection works, you can easily apply this knowledge elsewhere.

As for java config and annotations, they do allow for much quicker and cleaner development. XML is quite verbose, hard to maintain and is very prone to errors, in part because IDEs are generally more helpful when working with java based configuration. Perhaps that is why you read that XML is being deprecated. I would recommend to go for java/auto configuration rather than XML one, unless you really need to (or are interested in it).

Now onto how to do it. A complete (but minimal) working Spring example:

/* Bean definition

@Component tells Spring that this is a bean. There are a few similar annotations.
It will be discovered during the component scan, as it has @Component annotation */

package main.java.org.example;
import org.springframework.stereotype.Component;

@Component 
public class Greeting {
    private String greeting = "Hello";

    public String getGreeting() {
        return this.greeting;
    }

    public void setGreeting(String greeting) {
        this.greeting = greeting;
    }
}


/* Another bean definition.
It has another bean as a dependency, which we inject with a setter. */

package main.java.org.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class GreetingCollector {
    private Greeting greeting;

    /* This is how you do setter injection */
    @Autowired
    public void setGreeting(Greeting greeting) {
        this.greeting = greeting;
    }

    public String getGreeting() {
        return greeting.getGreeting();
    }
}


/* This is a minimal config class. 
@ComponentScan instructs to look for classes that are 
annotated with @Component annotation (in other words, beans) */

package main.java.org.example;    
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan
@Configuration
public class Config {}

If you want to do it explicitly:

package main.java.org.example;  
import main.java.org.example.GreetingCollector;
import main.java.org.example.Greeting;  
import org.springframework.context.annotation.Configuration;

@Configuration
public class Config {
    @Bean
    public Greeting greeting() {
        return new Greeting();
    }

    @Bean
    public GreetingCollector greetingCollector(Greeting greeting) {
        return new GreetingCollector(greeting);
    }
}

And if you want to run it just to see how it works:

import main.java.org.example.Config;
import main.java.org.example.GreetingCollector;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AppContext {
    public static void main(String args[]) {
        System.out.println("Configuring application context...");
        ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        GreetingCollector collector = (GreetingCollector) context.getBean("greetingCollector");
        System.out.println(collector.getGreeting());
    }
}

Naturally, Spring web application would be a bit different, but the basic injection idea is the same. First, you need to declare beans (either by using @Bean, @Component or any other annotation: see here and here for differences). You annotate either a setter or constructor (or even a field) with @Autowired, specify parameters (which do not necessarily need to be concrete classes - interfaces, abstract classes are fine, too), assign them to appropriate fields. Create a config class which takes cares of bean instantiation. You do not need to have your components in the same folder as config classes, as you can always specify where to look for components. Finally, if you want a more fine grained control, you can always declare beans explicitly in configuration class (so called JavaConfig, whereas @ComponentScan based config might sometimes be called autoconfig). This should be enough to get you started and give you vocabulary to search for more advanced stuff.

And of course, with Spring Boot everything is even more abstracted away/quicker.

2 of 2
1

However, I was told that xml is deprecated and all new applications should be done with java configuration

XML is not deprecated but annotations are there which makes life easy. Then why to go for plain old XML. Remember "Convention over Configuration"

Where should I be declaring the bean and how would I do it?

I think you should search google for annotations like @Component, @Configuration, @Bean. Read about them you'll understand

This is one of the examples I have seen, yet it is implemented with xml.

You would find many example implemented using XML as XML was widely used in earlier days of Spring. Now with the advent of Spring 4 and Spring Boot. Most of the developers don't use XML on a large scale.

🌐
Apps Developer Blog
appsdeveloperblog.com › home › spring framework › setter-based dependency injection in spring
Setter-based Dependency Injection in Spring - Apps Developer Blog
February 11, 2023 - In the UserServiceImpl class, we have defined a setter method for UsersRepository named setUsersRepository. The @Autowired annotation is used to tell Spring to automatically inject an instance of UsersRepository into this setter method. This is an example of Setter-based Dependency Injection.
Find elsewhere
🌐
Spring
docs.spring.io › spring-framework › reference › core › beans › dependencies › factory-collaborators.html
Dependency Injection :: Spring Framework
Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or a no-argument static factory method to instantiate your bean. The following example shows a class that can only be dependency-injected by using pure setter injection.
🌐
Java Guides
javaguides.net › 2018 › 06 › spring-dependency-injection-via-setter.html
Spring Dependency Injection via Setter Example
November 10, 2019 - It's time to demonstrate the usage of Setter-based dependency injection. To avoid decoupling always use interfaces or abstract base classes as an instance variable and setter method arguments. In this example, we have used the MessageService interface. import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import com.javadevsguide.springframework.di.service.MessageService; @Component public class SetterBasedInjection { private MessageService messageService; @Autowired @Qualifier("TwitterService") public void setMessageService(MessageService messageService) { this.messageService = messageService; } public void processMsg(String message) { messageService.sendMsg(message); } }
🌐
Spring
spring.io › blog › 2007 › 07 › 11 › setter-injection-versus-constructor-injection-and-the-use-of-required
Setter injection versus constructor injection and the use of @Required
July 11, 2007 - Specialization in an application does not occur as often in application code as it does in framework code for example--again the number of use cases in which application code is far less. We usually advise people to use constructor injection for all mandatory collaborators and setter injection for all other properties.
🌐
www.java4coding.com
java4coding.com › contents › spring › setter-injection
Setter Injection in Spring - java4coding
When setter injection is used presence of default constructor is mandatory a javabean class. The <property> element is used to describe one-setter method which should have one and only one parameter for particular property. All child tags of <property> elements are same as the child tags of <constructor-arg> element. And usage of child tags of <property> elements are same as that of child tags of <constructor-arg> element. Let's see the simple example to inject primitive and object-based values.
🌐
GeeksforGeeks
geeksforgeeks.org › advance java › spring-dependency-injection-with-example
Spring Dependency Injection with Example - GeeksforGeeks
There are two primary types of Spring Dependency Injection: Setter DI involves injecting dependencies via setter methods.
Published   1 week ago
🌐
Medium
medium.com › @greekykhs › springboot-tutorial-part-2-dependency-injection-5d464edec478
#SpringBoot : Tutorial Part 2 (Dependency Injection) | by Himaanshu Shukla | Medium
March 12, 2022 - The field injection uses reflection to set the values of private variables. Constructor injection happens at the time of creating the object itself. Whereas the setter Injection uses setters to set the value.
🌐
Medium
medium.com › spring-boot › dependency-injection-in-springboot-with-setter-and-constructor-injection-7880151b5e0f
Dependency Injection in Spring Boot with Setter and Constructor Injection | by Shagun | JavaToDev | Medium
September 13, 2024 - Spring Boot Dependency Injection in Spring Boot with Setter and Constructor Injection A detailed comparison of constructor-based and setter-based dependency injection in Spring Boot, with examples to …
🌐
Baeldung
baeldung.com › home › spring › wiring in spring: @autowired, @resource and @inject
Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung
May 11, 2024 - In order to verify that we injected the dependency by the match-by-name execution path, we need to change the value, yetAnotherFieldInjectDependency, that was passed in to the @Named annotation to another name of our choice. When we run the test again, a NoSuchBeanDefinitionException will be thrown. Setter-based injection for the @Inject annotation is similar to the approach used for the @Resource setter-based injection.
🌐
Springbyexample
springbyexample.org › examples › intro-to-ioc-basic-setter-injection.html
3. Basic Setter Injection
Example 3. SetterMessage · public class SetterMessage { private String message = null; /** * Gets message. */ public String getMessage() { return message; } /** * Sets message. */ public void setMessage(String message) { this.message = message; } } The property element is used to define the setter injection: ... <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="message" class="org.springbyexample.di.xml.SetterMessage"> <property name="message" value="Spring is fun."
🌐
Medium
medium.com › @miguelangelperezdiaz444 › dependency-injection-in-spring-constructor-property-or-setter-which-one-should-i-choose-d38be824c8c1
💉Dependency Injection in Spring: Constructor, Property, or Setter? Discover the Best Option for Your Project! | Medium
April 5, 2023 - In this example, the ... with (@Autowired). Setter Based Dependency Injection involves annotating a method with the @Autowired annotation. When Spring creates an object that ......
🌐
Educative
educative.io › home › courses › the complete guide to spring 6 and spring boot 3 › constructor and setter injection
Constructor and Setter Injection
To show the two different ways of dependency injection, we will create a copy of the RecommenderImplementation class and call it RecommenderImplementation2. One will be used to show constructor injection while the other will demonstrate setter injection. We will use the @Autowired annotation at different places in the code to direct Spring which injection type to use.
🌐
Smartprogramming
smartprogramming.in › tutorials › spring-framework › dependency-injection-using-setter-method-in-spring
Dependency Injection using Setter Method in Spring
Setter Method Injection is an effective method for injecting dependencies in Spring Framework. Learn how to use setter methods to set dependencies after object creation, providing flexibility and optional dependency injection.