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

2

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

    
asked by anonymous 27.12.2017 / 12:16

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 rather than let spring automatically do. 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, beans in spring are singletons, that is, one instance per container context.

@autowired is how you inject, that is, use your beans for the project.

    
15.01.2018 / 01:40