Engineering Full Stack Apps with Java and JavaScript
Create and execute a basic spring program using Java configuration.
We will create a simple class, configure it and test it. We will have a Java class annotated with @Configuration to hold bean configuration.
If you are using Maven, just copy paste below dependency into your pom file and all other required dependencies will be added automatically, as they are the transitive dependencies for below dependency.
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
Please use the latest version as available in the Spring website @ http://projects.spring.io/spring-framework.
PS: If you are new to maven. please first refer here.
JJWriter.java
package com.javajee.spring;
public class JJWriter {
public void write() {
System.out.println("Default Writer");
}
}
Our config class will look as below.
DemoConfig.java
package com.javajee.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class DemoConfig {@Bean (name = "jjwriter")
public JJWriter getJJWriter()
{
return new JJWriter();
}
}
The test class will look as below:
JJWriterWithConfigMain.java
package com.javajee.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class JJWriterWithConfigMain {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class);
JJWriter writer = context.getBean("jjwriter", JJWriter.class);
writer.write();
}
}