Java-based configuration
So far, you've seen how to configure a Spring bean using an XML configuration file. If you are familiar with using XML configuration, then I would say that there is no need to learn how to do Java-based configuration, because you want to achieve the same results, you can use other available configurations.
Java-based configuration options allow you to write most of Spring without having to configure XML, but some helpful Java-based annotations are explained as follows:
@Configuration and @Bean annotations
Annotated classes with @Configuration indicate that the class can use the Spring IoC container as the source for the bean definition. @Bean Note tells Spring that an annotation method with @Bean will return an object that should be registered as a Bean in the context of the Spring application.
Demo Example:
(1). Writing Helloworldconfig.java
Package Com.tutorialspoint; import org.springframework.context.annotation.*; @Configurationpublicclass helloworldconfig { @Bean public HelloWorld HelloWorld () { return New HelloWorld (); }}
The above code is equivalent
<beans> Class= "Com.tutorialspoint.HelloWorld"/></beans>
(2) Writing Helloworld.java
Package Com.tutorialspoint; Public class HelloWorld { private String message; Public void setmessage (String message) { this.message = message; } Public void GetMessage () { System.out.println ("Your message:" + message);} }
(3) Writing Mainapp.java
PackageCom.tutorialspoint;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.annotation.AnnotationConfigApplicationContext; Public classMainapp { Public Static voidMain (string[] args) {ApplicationContext ctx=NewAnnotationconfigapplicationcontext (Helloworldconfig.class); HelloWorld HelloWorld= Ctx.getbean (HelloWorld.class); Helloworld.setmessage ("Hello world!"); Helloworld.getmessage (); }}
The results of the operation are as follows:
The Java-based configuration of Spring (eight)