How autowiring works in Spring

0 votes

Say I have a service class called UserServiceImpl that implements UserService interface.

How can this be @Autowired?

And in my Controllers, how would I instantiate an instance of this service?

Would I just do the following?

UserService userService = new UserServiceImpl();
Jan 11, 2019 in Java by Sushmita
• 6,920 points
18,637 views

3 answers to this question.

0 votes

Depends on whether you went the annotations route or the bean XML definition route.

Say you had the beans defined in your applicationContext.xml:

<beans ...>

    <bean id="userService" class="com.foo.UserServiceImpl"/>

    <bean id="fooController" class="com.foo.FooController"/>

</beans>

The autowiring happens when the application starts up. So, in fooController, which for arguments sake wants to use the UserServiceImpl class, you'd annotate it as follows:

public class FooController {

    // You could also annotate the setUserService method instead of this
    @Autowired
    private UserService userService;

    // rest of class goes here
}

When it sees @Autowired, Spring will look for a class that matches the property in the applicationContext, and inject it automatically. If you have more than 1 UserService bean, then you'll have to qualify which one it should use.

Hope this helps!

Enroll in Spring course online to learn more about it.

Thanks!

answered Jan 11, 2019 by Daisy
• 8,140 points

edited Mar 4, 2022 by Sarfaraz
0 votes

Depends on whether you went the annotations route or the bean XML definition route.

Say you had the beans defined in your applicationContext.xml:

<beans ...>

    <bean id="userService" class="com.foo.UserServiceImpl"/>

    <bean id="fooController" class="com.foo.FooController"/>

</beans>

The autowiring happens when the application starts up. So, in fooController, which for arguments sake wants to use the UserServiceImpl class, you'd annotate it as follows:

public class FooController {

    // You could also annotate the setUserService method instead of this
    @Autowired
    private UserService userService;

    // rest of class goes here
}

When it sees @Autowired, Spring will look for a class that matches the property in the applicationContext, and inject it automatically. If you have more than 1 UserService bean, then you'll have to qualify which one it should use.

answered Jan 11, 2019 by Daisy
• 8,140 points
0 votes

First, and most important - all Spring beans are managed - they "live" inside a container, called "application context".

Second, each application has an entry point to that context. Web applications have a Servlet, JSFuses a el-resolver, etc. Also, there is a place where the application context is bootstrapped and all beans - autowired. In web applications this can be a startup listener.

Autowiring happens by placing an instance of one bean into the desired field in an instance of another bean. Both classes should be beans, i.e. they should be defined to live in the application context.

What is "living" in the application context? This means that the context instantiates the objects, not you. I.e. - you never make new UserServiceImpl() - the container finds each injection point and sets an instance there.

In your controllers, you just have the following:

@Controller // Defines that this class is a spring bean
@RequestMapping("/users")
public class SomeController {

    // Tells the application context to inject an instance of UserService here
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public void login(@RequestParam("username") String username,
           @RequestParam("password") String password) {

        // The UserServiceImpl is already injected and you can use it
        userService.login(username, password);

    }
}

A few notes:

  • In your applicationContext.xml you should enable the <context:component-scan> so that classes are scanned for the @Controller, @Service, etc. annotations.
  • The entry point for a Spring-MVC application is the DispatcherServlet, but it is hidden from you, and hence the direct interaction and bootstrapping of the application context happens behind the scene.
  • UserServiceImpl should also be defined as bean - either using <bean id=".." class=".."> or using the @Service annotation. Since it will be the only implementor of UserService, it will be injected.
  • Apart from the @Autowired annotation, Spring can use XML-configurable autowiring. In that case all fields that have a name or type that matches with an existing bean automatically get a bean injected. In fact, that was the initial idea of autowiring - to have fields injected with dependencies without any configuration. Other annotations like @Inject, @Resource can also be used.
answered Jan 11, 2019 by developer_1
• 3,350 points

Related Questions In Java

0 votes
1 answer

I am learning looping statements. Can you tell me how 'for-each' works in Java?

While programming we often write code that ...READ MORE

answered Apr 17, 2018 in Java by Rishabh
• 3,620 points
936 views
0 votes
0 answers

Can anyone explain Autowiring in Spring ?

Say I have a service class called UserServiceImpl that ...READ MORE

Jan 11, 2019 in Java by Sushmita
• 6,920 points
666 views
0 votes
2 answers

How to log SQL statements in Spring Boot?

HI.. try using this in your properties file: logging.level.org. ...READ MORE

answered Sep 25, 2020 in Java by SRI

edited Sep 25, 2020 by Sirajul 4,932 views
0 votes
1 answer

How to redirect to an external URL from controller action in Spring MVC?

Hello @kartik, You can do it with two ...READ MORE

answered May 22, 2020 in Java by Niroj
• 82,840 points

edited Mar 4, 2022 by Sarfaraz 26,897 views
0 votes
1 answer

Bean life cycle in Spring Bean Factory Container

Bean life cycle in Spring Bean Factory ...READ MORE

answered Aug 30, 2018 in Java by code.reaper12
• 3,500 points
3,298 views
0 votes
1 answer

How to download a file from spring controllers?

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET) public void ...READ MORE

answered Sep 4, 2018 in Java by code.reaper12
• 3,500 points
2,957 views
0 votes
1 answer

Understanding Spring @Autowired usage

TL;DR The @Autowired annotation spares you the need ...READ MORE

answered Nov 30, 2018 in Java by Sushmita
• 6,920 points
1,845 views
0 votes
1 answer

Why is my Spring @Autowired field null?

If you are not coding a web ...READ MORE

answered Dec 27, 2018 in Java by Daisy
• 8,140 points

edited Mar 4, 2022 by Sarfaraz 18,784 views
0 votes
5 answers

How to compare Strings in Java?

String fooString1 = new String("foo"); String fooString2 = ...READ MORE

answered Jul 12, 2018 in Java by Daisy
• 8,140 points
2,552 views
0 votes
2 answers

How to create a 2-D array in java?

int[][] multi = new int[5][]; multi[0] = new ...READ MORE

answered Jul 16, 2018 in Java by Daisy
• 8,140 points
1,552 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP