What in the world are Spring beans?
Asked Answered
P

17

534

I am yet to find a high-level definition of Spring beans that I can understand. I see them referenced often in Grails documentation and books, but I think that understanding what they are would be beneficial. So

  1. What are Spring beans?
  2. How can they be used?
  3. Do they have something to do with Dependency Injection?
Preamplifier answered 19/6, 2013 at 14:5 Comment(6)
Grails is built on Spring. If you're not familiar with Spring, I suggest you at least read some material on it so you understand the technologies you are using.Jopa
I think the comments here suffer from the same problem the OP sees in the references in Grails docs and books: they are only easy for people who already know what they mean. I find that the Wikipedia's article describes it much better for a beginner.Humbert
@MarcoForberg one of the reasons that ancient version of Spring is the top hit on Google is because people keep linking to it from places like SO... static.springsource.org/spring/docs/3.2.x/… would be a better place to start these days.Marable
+1 @IanRoberts. Here is the current one.Whortleberry
It doesn't help that they introduce IoC by saying that IoC is also known as DI. They are related yes, but IoC is much broader.Simmers
I liked this description of Spring beans: baeldung.com/spring-beanPoston
M
255

The Spring core technologies reference documentation describes what beans are.

Per the Introduction to the Spring IoC Container and Beans section (where "IoC" means "inversion of control"):

In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans, and the dependencies among them, are reflected in the configuration metadata used by a container.

Beans and scope are described in the Bean Scopes section:

When you create a bean definition, you create a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, as with a class, you can create many object instances from a single recipe.

You can control not only the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition but also control the scope of the objects created from a particular bean definition. This approach is powerful and flexible, because you can choose the scope of the objects you create through configuration instead of having to bake in the scope of an object at the Java class level. Beans can be defined to be deployed in one of a number of scopes.

Menendez answered 19/6, 2013 at 14:8 Comment(6)
So these are objects that the container manages and I don't have to touch, but if I want access to a bean to maybe call some methods or retrieve properties, then I can "ask" Spring for the bean?Preamplifier
@grantmc Yes the objects you want to handle through container, their creation their retreival etcMenendez
@grantmc It's sort of like that, except the inversion of control thing is supposed to be understood as the contrary of "ask": instead of "asking" for things, you "declare" that you'll need it. And then, when you startup the app, the framework will check all declarations and set the appropriate instance.Humbert
@elias How do I declare that I need it? Is it when I'm using @Autowired? Or simply when I do my imports?Whereof
It would be helpful to define what IoC means for Spring newcomers.Basilbasilar
@lucas Agreed. IoC is "Inversion of Control". See excellent Q&A: What is Dependency Injection and Inversion of Control in Spring Framework? and What is Inversion of Control?.Misbecome
H
184

Spring beans are just instance objects that are managed by the Spring container, namely, they are created and wired by the framework and put into a "bag of objects" (the container) from where you can get them later.

The "wiring" part there is what dependency injection is all about, what it means is that you can just say "I will need this thing" and the framework will follow some rules to get you the proper instance.

For someone who isn't used to Spring, I think Wikipedia Spring's article has a nice description:

Central to the Spring Framework is its inversion of control container, which provides a consistent means of configuring and managing Java objects using reflection. The container is responsible for managing object lifecycles of specific objects: creating these objects, calling their initialization methods, and configuring these objects by wiring them together.

Objects created by the container are also called managed objects or beans. The container can be configured by loading XML files or detecting specific Java annotations on configuration classes. These data sources contain the bean definitions which provide the information required to create the beans.

Objects can be obtained by means of either dependency lookup or dependency injection. Dependency lookup is a pattern where a caller asks the container object for an object with a specific name or of a specific type. Dependency injection is a pattern where the container passes objects by name to other objects, via either constructors, properties, or factory methods.

Humbert answered 19/6, 2013 at 14:13 Comment(6)
An instance is merely another word for objects. When you use "object instances" aren't you saying object objects?Bor
Interesting question. According to Wikipedia I should say "instance objects" instead: en.wikipedia.org/wiki/Instance_(computer_science)Humbert
The rabbit hole goes deeper.Bor
I've realized today that "object objects" (and therefore object instances) actually make sense to me because I'm used to languages where a class is also an object (so you have class objects, and, well, "object" objects). Anyway, I've updated the description to use "instance objects" as per the Wikipedia article. ^^Humbert
So, is Spring bean a class or instance of a classTjon
@Ruizhi a regular object, i.e., an instance of a class -- this discussion was a sidetrack about using the correct expression to refer to an object. :)Humbert
D
116

First let us understand Spring:

Spring is a lightweight and flexible framework.

Analogy:
enter image description here

Java Beans are classes that encapsulate many objects into a single object (the bean). The name "Bean" was given to encompass this standard, which aims to create reusable software components for Java.

Spring Bean: is an object, which is created, managed and destroyed in Spring Container. We can inject an object into the Spring Container through the metadata(either xml or annotation), which is called inversion of control.

Analogy: Let us assume farmer is having a farmland cultivating by seeds(or beans). Here, Farmer is Spring Framework, Farmland land is Spring Container, Beans are Spring Beans, Cultivating is Spring Processors.

enter image description here

Like bean life-cycle, spring beans too having it's own life-cycle.

enter image description here

enter image description here

img source

Following is sequence of a bean lifecycle in Spring:

  • Instantiate: First the spring container finds the bean’s definition from the XML file and instantiates the bean.

  • Populate properties: Using the dependency injection, spring populates all of the properties as specified in the bean definition.

  • Set Bean Name: If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method.

  • Set Bean factory: If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.

  • Pre-Initialization: Also called post process of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.

  • Initialize beans: If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.

  • Post-Initialization: – If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

  • Ready to use: Now the bean is ready to use by the application

  • Destroy: If the bean implements DisposableBean, it will call the destroy() method

Desmonddesmoulins answered 23/3, 2018 at 6:26 Comment(3)
I'm sorry, but saying that Spring is a lightweight [...] framework. is just absolutely ridiculous.Kasten
@Kasten hmm, I'm not an expert, but I've heard that Spring is a lightweight framework many times and I've read it in many places that it is. But as I said I don't have much knowledge. Can you share some info on how you know it's not? So I can know is it lightweight or not. Thank you.Oliviaolivie
@Oliviaolivie It is lighter weight in comparison to what came before it. Spring documentation as far back as 1.1.1. from 2004 states: "Spring provides a light-weight solution for building enterprise-ready applications…" Here's a StackOverflow answer which addresses the perceived relative heaviness: https://mcmap.net/q/74861/-what-makes-the-spring-framework-a-lightweight-containerMannuela
G
25

A Bean is a POJO(Plain Old Java Object), which is managed by the spring container.

Spring containers create only one instance of the bean by default. 
This bean it is cached in memory so all requests for the bean will return a shared reference to the same bean.

The @Bean annotation returns an object that spring registers as a bean in application context.
The logic inside the method is responsible for creating the instance.

When do we use @Bean annotation?

When automatic configuration is not an option. For example when we want to wire components from a third party library, because the source code is not available so we cannot annotate the classes with @Component.

A Real time scenario could be that someone wants to connect to Amazon S3 bucket. Because the source is not available he would have to create a @bean.

@Bean
public AmazonS3 awsS3Client() {
    BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsKeyId, accessKey);
    return AmazonS3ClientBuilder.standard().withRegion(Regions.fromName(region))
            .withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
}

Source for the code above -> https://www.devglan.com/spring-mvc/aws-s3-java

Because I mentioned @Component Annotation above.

@Component Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and class path scanning.

Component annotation registers the class as a single bean.

Galipot answered 25/2, 2020 at 13:7 Comment(0)
W
24

Well you understood it partially. You have to tailor the beans according to your need and inform Spring container to manage it when required, by using a methodology populalrly known as IoC (Inversion of Control) coined by Martin Fowler, also known as Dependency Injection (DI).

You wire the beans in a way, so that you do not have to take care of the instantiating or evaluate any dependency on the bean. This is popularly known as Hollywood Principle.

Google is the best tool to explore more on this in addition to the links you would get flooded with here in this question. :)

Whortleberry answered 19/6, 2013 at 14:21 Comment(1)
Cannot not point out that IoC is the concept, and DI is (one of) the technique which can be used to achieve IoC, they are not replaceable definitions.Lethargy
M
14

Spring beans are classes. Instead of instantiating a class (using new), you get an instance as a bean cast to your class type from the application context, where the bean is what you configured in the application context configuration. This way, the whole application maintains singleton-scope instance throughout the application. All beans are initialized following their configuration order right after the application context is instantiated. Even if you don't get any beans in your application, all beans instances are already created the moment after you created the application context.

Methodize answered 12/4, 2017 at 1:12 Comment(2)
Beans are not classes, but objects as instances of classes, managed by a container implementation.Pharisaic
This gave me a better understanding of beans. So basically it is to instantiate a class without using the famous "new" keyword. Thank you.Neolatin
C
12
  • Spring beans are just object instances that are managed by the Spring IOC container.

  • Spring IOC container carry the Bag of Bean.Bean creation,maintain and deletion are the responsibilities of Spring Container.

  • We can put the bean in to Spring by Wiring and Auto Wiring.

  • Wiring mean we manually configure it into the XML file.

  • Auto Wiring mean we put the annotations in the Java file then Spring automatically scan the root-context where java configuration file, make it and put into the bag of Spring.

Catchment answered 14/3, 2017 at 6:41 Comment(0)
N
11

Spring have the IoC container which carry the Bag of Bean ; creation maintain and deletion are the responsibilities of Spring Container. We can put the bean in to Spring by Wiring and Auto Wiring. Wiring mean we manually configure it into the XML file and "Auto Wiring" mean we put the annotations in the Java file then Spring automatically scan the root-context where java configuration file, make it and put into the bag of Spring.

Here is the detail URI where you got more information about Beans

Newtonnext answered 11/12, 2014 at 10:12 Comment(0)
E
11

In terms of a Spring boot application, a bean is simply a Java object which is created by Spring framework when the application starts.

The purpose of the object can be pretty much anything - a configuration, a service, database connection factory etc. - Spring doesn't really care.

Most beans depend on other beans to work, for example an entity manager might need a database connection. Spring framework is able to figure out how the beans should be wired together automatically. From your point of an application developer, you just have to declare the beans you need and they "magically" appear in your application ready to use.

Endometriosis answered 28/8, 2020 at 16:49 Comment(0)
S
2

In Spring, those objects that form the backbone of your application and that are managed by the Spring IoC container are referred to as beans. A bean is simply an object that is instantiated, assembled and otherwise managed by a Spring IoC container;

Sheffie answered 14/7, 2014 at 7:14 Comment(0)
B
2

The XML configuration of Spring is composed of Beans and Beans are basically classes. They're just POJOs that we use inside of our ApplicationContext. Defining Beans can be thought of as replacing the keyword new. So wherever you are using the keyword new in your application something like:

MyRepository myRepository =new MyRepository ();

Where you're using that keyword new that's somewhere you can look at removing that configuration and placing it into an XML file. So we will code like this:

<bean name="myRepository " 
      class="com.demo.repository.MyRepository " />

Now we can simply use Setter Injection/ Constructor Injection. I'm using Setter Injection.

public class MyServiceImpl implements MyService {
    private MyRepository myRepository;
    public void setMyRepository(MyRepository myRepository)
        {
    this.myRepository = myRepository ;
        }
public List<Customer> findAll() {
        return myRepository.findAll();
    }
}
Bridal answered 30/11, 2018 at 7:17 Comment(0)
C
1

For Spring, all objects are beans! The fundamental step in the Spring Framework is to define your objects as beans. Beans are nothing but object instances that would be created by the spring framework by looking at their class definitions. These definitions basically form the configuration metadata. The framework then creates a plan for which objects need to be instantiated, which dependencies need to be set and injected, the scope of the newly created instance, etc., based on this configuration metadata.

The metadata can be supplied in a simple XML file, just like in the first chapter. Alternatively, one could provide the metadata as Annotation or Java Configuration.

Book: Just Spring

Curbing answered 17/7, 2017 at 9:35 Comment(0)
N
0

For a Java class to be usable as a Java bean, its setter- and getter-method names need to be as per the JavaBean guidelines (also called design patterns) for properties. If such a Java class is instantiable & manageable by the Spring IoC container, it is a Spring bean. To achieve this, the programmer wires the class as a bean definition of a suitable scope by using XML config files or annotations or a mix of both. The programmer can create new Spring beans out of existing Spring beans by wiring further by passing the latter to constructor-arguments of the former either as string-names as <idref> elements or by dependency injection (it can be recursive).

This answer may be read in conjunction with my this SO answer to get more background information.

Noah answered 25/8, 2022 at 9:8 Comment(0)
D
0

Beans are instances of a class managed by Spring Container.

Deprave answered 30/10, 2022 at 17:55 Comment(0)
D
0

Spring is a Java framework that facilitates for many needs and links to Spring are already posted in other answers, so I will not repost them here. Good tutorial here. Among other things it removes the need for you to take care and create dependencies for everything in your classes, It does this using using IoC (Inversion of Control). You create the rules and the container will then facilitate your needs by taking care of dependencies and creating objects when needed. These container managed objects are called Beans. This removes the need for using 'new' and figuring our where to get the instance of an object in you own class. So DataSource db = new DataSource("all the parameters you need. What if this is production env?!?") becomes essentially DataSource db = context.getBean(MySpecializedDataSource.class); and Spring decides according to your configuration and properties what instance to get for you.

Lets say you are creating a servlet that responds to HTTP requests and gets data from a database. Normally you would do everything by hand and extend HttpServlet and implement your logic in doGet() and doPost(). Then you would create a jdbc connection and get the data you need. Then you print out HTML maybe with something like response.getWriter().println("<html>Hello "+user.toString()+"</html>");

In Spring (and Spring Boot) you can get all this by using Annotations and Beans, without writing it all by yourself. This makes creating software and features a lot faster and without errors and implementation differences in every servlet.

I will continue the example with Spring Boot, because it makes things even more simple but we are still talking about Spring essentially.

In Spring Boot you would declare your servlet with Annotation to add functionality to it and also to tell Spring the rules you want to use for configuration. I would use

@Controller //This means it is also a Bean and I want Spring container to create, manage and destroy these objects. Just create one when I need like when a HTTP request arrives to mysite.com/
public class NameController
{
    @Autowired //This is a Bean. It's configuration rules are somewhere in ApplicationContext. Spring go find them and get me an/the instance
    private UserService userService;

    @Autowired // I need access to the HTTP request. Go get it for me. 
    private HttpServletRequest request;

    String fullName = userService.findUserById(reguest.getParameter("id")); //fullName is not a Bean
    
    @Value("${myStrings.const1}") //not a Bean by itself, but a PropertyPlaceHolder bean will go and get this value from somewhere for me
    private String someString;
    
    @GetMapping("/") //No need to define HTTP handlers by hand or write doGet(). 
    public String index() {
        return "<html>Greetings from Spring Boot! "+fullName+" "+someString+" </html>";
    }
}

//UserService would then define a Datasource and what to query

@Component // This is also a bean. Create and manage when needed
public class UserService {


    private DataSource dataSource; //no need for initialization like 'new'

    public UserService(@Autowired DataSource dataSource) { // Use the DataSource I defined in my Bean configuration in MyApplicationContextConfiguration (or where ever you find a configuration in the ApplicationContext)
        this.dataSource = dataSource;
    }
    
    public String findById(Integer id) {
        try (Connection connection = dataSource.getConnection()) { 
               PreparedStatement selectStatement = connection.prepareStatement("select * from users where id =  ?");
               // TODO execute query. Maybe wrap inside @Transactional to get DB commits if it is an update etc
        }
    }
}

/*
Then you would define the rules that the container follows when it creates and manages these Beans. You have to declare it somewhere right?
You would then create the Bean definitions somewhere like in ApplicationContextConfiguration that you would use to create your ApplicationContext (the container).
You could add configurations with XML or by any means that Spring provides. 
/*

package com.my.examples;

@Configuration //This defines the Beans as a ApplicationContextConfiguration
@ComponentScan  // please Spring go through all packages under com.my.examples and find anything that looks like a bean and create them if needed
public class MyApplicationContextConfiguration {

    @Bean //this is a Bean and it is used inside my Components, Controllers etc. Create and manage it when needed
    @Scope("singleton") //I want to be absolutely sure, that there is only one instance present in the container. Just an example. You might want several of these on a busy server
    public DataSource dataSource() {
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setUser("root"); //you can move this outside your project to properties files later on, so it stays out of Git and can easily be change per environment
        dataSource.setPassword("s3cr3t");
        dataSource.setURL("jdbc:mysql://localhost:3306/myDatabase");
        return dataSource;
    }
    
    /* no need for this anymore! It is being created by the @Component annotation
    @Bean
    public UserService userService() { 
        return new UserService(dataSource());
    }
    */
}

/*
Then later on you can change this @Bean configuration so, that it does not contain hard coded values. You could use something like @Resource to define that these values are in someProps.properties file and then you can easily use different properties depending if you are in test or production.
You can also access any type of resource you need even outside the project folders. You could even use REST API to ask some other service for the configuration.
You add a package in pom.xml and then use the proper Annotation to get the feature you want inside your code.
JUnit for testing, RabbitMQ for messaging between beans or what ever the need is. You can add REST API support for your application in minutes with @RestController and the Spring Web package. Persistance of Java objects to Hibernate by adding JPA and H2
*/

The Back Story

I'll give some backround first and how I explained these Beans to myself. I have done J2EE programming back in the day for banks and such, so I got something like 7 years of Java experience in my pocket. When I was doing stuff there were Annotations in Java, but nobody was using them. There was no enum yet. So now ~20 years later I needed some software to automate a company's business. "I can do it myself with Java!" I thought and Googling around a bit I found out that Spring and Spring Boot is the way to go. Now after a week I finally got the Spring Boot Maven project to compile. I think I understand some of the methodology now. I don't know if the code actually runs, I wrote it as I undertand the Spring concept

Devilfish answered 25/8, 2023 at 8:14 Comment(2)
any affiliation with the tutorial you linked? /help/promotionConfiding
no affiliation. It made sense to me after all these other posts linking straight to spring documentation. Those might technically be considered answers to the question, but I feel that they don't help much in the beginning of your Spring journey. 6 hours of debugging last night with IllegalState exceptions in the application start. Had to explain Beans to myself first to get it working...Devilfish
P
0

According to the Spring Documentation, "...A bean definition is essentially a recipe for creating one or more objects. The container looks at the recipe for a named bean when asked and uses the configuration metadata encapsulated by that bean definition to create (or acquire) an actual object."

It, therefore, follows from this explanation that a bean is an object or instance created by the IoC container and not a class as some persons seem to posit.

Reference

Prelect answered 6/11, 2023 at 19:46 Comment(0)
D
-2

In short, Beans are called Runtime Objects, and if a Runtime Object is managed by the Spring then it is called Spring Bean.

We can consume these runtime objects without using the new keyword(used to create objects) by using the @Autowired keyword.

@Component //this annotation is used to create the spring beans
public class Component {
    private String username;
    private String email;

    public Component(String username, String email){
       this.username = username;
       this.email = email;    
    }

    public void setUsername(String username){
       this.username = username;
    }

    public String getUsername(){
       return username;
    }

    public void setEmail(String email){
       this.email = email;
    }

    public String getEmail(){
       return email;
    }
}

Now below, without instantiating the object we can use the methods of Component because Spring is managing it with the help of @Component annotation.

public class Service{

    @Autowired
    private Component component;

    private void callingComponentMethods(){
        component.setUsername("TestUser"); //setting the value for username
        System.out.println(component.getUsername); //printing the above set value
    }
}
Drouin answered 19/6, 2023 at 11:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.