Uses of @Bean and @Autowired notations and what are they for?

Asked

Viewed 1,812 times

2

I have difficulty understanding these two notations and what they are for. I read documentation and some answers about, and from what I understood @Bean would be an instance creation of a class, and @Autowired would use that instance. Is that it? Could you compare these notations to the use of the Singleton standard? There would be some example of a situation I would have to use?

1 answer

1


@Component, @Service and @Repository are used when you want your Beans to be auto configured by spring.

@Bean is used when you need to explicitly configure the bean instead of automatically letting spring do it. For example, for Datasource configuration:

@Bean
    public DataSource getDataSource() {
        DataSource ds = null;
        try {
            InitialContext context = new InitialContext();
            ds = (DataSource) context.lookup("jdbc/seuLockUp");
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return ds;
    }

By default, the Beans in spring are singletons, i.e., one instance per container context.

@autowired is how you inject, ie, use your Beans by the project.

  • A link to the documentation helps. I believe you can find a link to some Baeldung tutorial that covers these annotations in general

Browser other questions tagged

You are not signed in. Login or sign up in order to post.