简体   繁体   中英

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.

To create a bean of AccountManager do following:

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

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 ;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM