Is there anyway to eliminate spring-context xml and turn on annotations programatically?

257 Views Asked by At

I am new bee in spring and was playing with 'Autowired' annotation in my small test program. So far, I have learned that to make 'Autowired' annotation work we need to turn it on from the spring- context xml using the tag:

<context:annotation-config />

I was wondering if there is any way to eliminate xml and turn on annotation from program.

Here is my spring program that is working with spring context defined in xml .

SpringContext.xml:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:context="http://www.springframework.org/schema/context"
            xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">


            <context:annotation-config />

            <!-- bean definitions go here -->

            <bean id="mainClass" class="com.myproject.spring.MyTester" />
            <bean id="student" class="com.myproject.spring.model.Student" scope="prototype" />
</beans>

My Bean:

package com.myproject.spring.model;



public class Student
{
    private String name = "Johhn Hasel";


    public String getName()
    {
        return name;
    }


    public void setName( String name )
    {
        this.name = name;
    }

    @Override 
    public String toString() {
        return name;
    }

}

And my main class for this application :

package com.myproject.spring;

import com.myproject.spring.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTester
{

    @Autowired
    private Student student;


    public static void main( String[] args )
    {

       ApplicationContext context = new ClassPathXmlApplicationContext("SpringContext.xml");
        MyTester mtster = context.getBean( MyTester.class );

        System.out.println(mtster.student.toString()); 

    }



}
2

There are 2 best solutions below

0
On BEST ANSWER

If you have a pure standalone application you need at minimum to

  1. annotate your student class with @Component
  2. Annotate your MyTester class with @ComponentScan and @Configuration
  3. Exchange the ClassPathXmlApplicationContext(..) with new AnnotationConfigApplicationContext(MyTester.class)

What happen behind the scenes is

  1. that you mark your Student as a class available for auto-discovery
  2. set the MyTester class as the starting point for scanning components and as a class which may contain configurations like @Bean definitions
  3. Tell Spring to use the Annotation driven configuration with the starting point in MyTester class
0
On

Put the following in your servlet xml file:

   <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

You can then have a java class to define your configuration which will be annotated with the @Configuration annotation.

Example of an annotated config class:

@Configuration
@ComponentScan(basePackages = "com.myproject.spring")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/pages/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Bean
    public Student student() {
        return new Student();
    }

}

You will also need to annotate your Student bean class with the @Component annotation.

Example:

@Component
public class Student {
...
}

If you prefer, you can refer to your bean config using the below instead of defining the annotation config context in your servlet xml.

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MvcConfiguration.class);