biroshima
biroshima

Reputation: 71

How to create a Spring Bean using existing library

I'm new to Spring and am using an existing Spring library/api. All beans are configured in java classes, ie. no xml, and the existing configuration comes with one line in the main method:

SpringApplication.run(ServerExchange.class, args);

The library deals with the protocols to interface with a private server, I've been able to create normal instances of classes, ie:

AccountManager aM = new AccountManager()

however the configuration that's meant to be autowired into each class, such as the AccountManager, isn't being done as it's intended to be created as a "bean", so when I go to use the AccountManager, it's dependencies that are @Autowired are null

I've been looking online and trying to find an example of how to go from the first given line in the main method however what I can find online is mainly based around either xml or an "ApplicationContext". I'm not sure how to take the first step and simply create a bean, can anyone please provide an example of the code to create an AccountManager bean?

Thanks in advance.

Edit: To clarify, I'm interested in the code required in the main method of how to get the instance of it once the beans have been set up in their respective classes.

Upvotes: 1

Views: 4052

Answers (3)

Md khirul ashik
Md khirul ashik

Reputation: 153

If you want to configure been at class, you can do it as follow.

@Configuration
public class AppConfig {
   @Bean 
public AccountManager accountManager() {
    return new AccountManager();
  }
}

Or If you wanna use xml then

<beans>
   <bean id = "accountManager" class = "packageName.AccountManager" />
</beans>

Then you can use it in a class as follows.

@Autowired
AccountManager accountManager ;

Upvotes: 2

Monzurul Shimul
Monzurul Shimul

Reputation: 8396

To create a bean of AccountManager do following:

@Bean
public AccountManager accountManager() {
    return new AccountManager();
}

Upvotes: 1

Bruno Delor
Bruno Delor

Reputation: 308

If you need any field to be autowired in an object you cannot instantiate it with new because when you do so Spring don't know about it.

You can do the following :

class MyClass{
    @Autowired
    ApplicationContext applicationContext;

    public void method(){
        AccountManager ac = applicationContext.getBean(AccountManager.class);
    }
}

if your AccountManager is known by Spring. With an annotation on the class like @Component

As I'm not a user of Spring-boot in this way I found here : How to get bean using application context in spring boot how to get ApplicationContext in a different way than the one I'm using

Upvotes: 0

Related Questions