Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we need xml file for doing Spring configuration using Annotation?

I was reading about the ways of doing Spring configuration and came to know that there are three ways of doing the same viz:

1) Plain XML based.
2) Using annotation based.
3) Java Based Configuration.

I am comfortable with approach #1 viz. pure XML based.

Now, I tried to use the approach #2 viz. Using annotation based.

For example:

@Component("circleID")
public class Circle {

    @Autowired
    private Point point;

    @Override
    public String toString() {
        return "Circle [point=" + point + "]";
    }
}

I expected Using Annotation there won't be any need of any xml file, but we still to have XML file for the following.

<context:annotation-config/>
<context:component-scan base-package="com.example.point , com.example.shapes" />

So isn't using annotations approach we are providing information in parts, some by XML and some by Annotations?

I am not clear on this, can anyone help me in getting this doubt cleared?

like image 879
CuriousMind Avatar asked Apr 27 '26 09:04

CuriousMind


1 Answers

XML is not required for Spring configuration. You can configure Spring with pure Java-based configuration (annotations).

For example, instead of using the XML you posted in your question you can create a class with @Configuration and @ComponentScan annotations:

@Configuration
@ComponentScan(basePackages = {"com.example.point", "com.example.shapes"})
public class MySpringConfig {

    public static void main(String[] args) {
        // Create Spring ApplicationContext from annotation config
        ApplicationContext context =
                new AnnotationConfigApplicationContext(MySpringConfig.class);

        // ...
    }
}

See Java-based container configuration in the Spring Framework reference documentation.

like image 195
Jesper Avatar answered Apr 29 '26 06:04

Jesper