Spring Initialization – Issues in Different Environments

initializationspring

I have some questions about spring's initialization in different environment.

1. In web container context, such as tomcat.

I knew that spring can be initialized by declaring

org.springframework.web.context.ContextLoaderListener in <listener-class> field.

It will be initialized automatically when tomcat is started. (I think this is right :-) )

2. In JUnit context

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:appContext.xml")

annotations can be used to initialize the Spring context.

Under these two cases, we can use such as

@Autowired 
private ServiceDao serviceDao;

to use the serviceDao, and we almost never used the ApplicationContext.getBean() method.

3. In a common J2SE environment

Should I must initialize the spring context manually,

ApplicationContext appContext = new FileSystemXmlApplicationContext(xx.xml)

and then use appContext.getBean(XX) to get the bean?

in this case, can @Autowired be used?

How to do this?

Updated:
I try the spring-boot, I think the variable can be autowired, because the class is annotated with @Component, and with the @ComponentScan in main class, the variable can be autowired.

But I used spring xml before, and I have some injection like this, I don't know how to autowire the variable.

<bean id="XXXMap" class="com.xx">
     <property name="handlerMap">
        <map>
            <entry key="XXX" value="YYY"/>
        </map>
    </property>
</bean>

use the @component, I believe XXXMap can be autowired, but how the map is initialized?

Best Answer

Yes, you can use @Autowired no matter how you create the application context.

There are several ways to create an application context in a standalone application. You can of course still use the traditional XML configuration files but an alternative option worth considering is spring-boot. It allows you to create completely annotation driven applications that mostly rely on conventions over configuration. Bootstrapping a simple standalone application reduces to:

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Main implements CommandLineRunner {

    @Autowired
    private UserService userService;

    public void run(String... args) throws Exception {
        System.out.println(userService.findUser(42L));
    }   

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

}