In this recipe, we will build a standard Java application (not a web application) using Spring. We will:
In this section, we will cover the steps to use Spring in a standard (not web) Java application.
Open Maven's pom.xml
configuration file at the root of the project. Select the pom.xml tab to edit the XML source code directly. Under the project
XML node, define the Java and Spring versions and add the Spring Core dependency:
<properties> <java.version>1.8</java.version> <spring.version>4.1.5.RELEASE</spring.version> </properties> <dependencies> <!-- Spring Core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> </dependencies>
Create the
com.springcookbook.config
Java package; in the left-hand side pane Package Explorer, right-click on the project and select New | Package….In the
com.springcookbook.config
package, create theAppConfig
class. In the Source menu, select Organize Imports to add the needed import declarations:@Configuration public class AppConfig { }
Create a User
Java class with two String
fields:
public class User { private String name; private String skill; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSkill() { return skill; } public void setSkill(String skill) { this.skill = skill; } }
In the AppConfig
class, define a User
bean:
@Bean public User admin(){ User u = new User(); u.setName("Merlin"); u.setSkill("Magic"); return u; }
Create the
com.springcookbook.main
package with theMain
class containing themain()
method:package com.springcookbook.main; public class Main { public static void main(String[] args) { } }
In the
main()
method, retrieve the User singleton and print its properties:AnnotationConfigApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class); User admin = (User) springContext.getBean("admin"); System.out.println("admin name: " + admin.getName()); System.out.println("admin skill: " + admin.getSkill()); springContext.close();
We created a Java project to which we added Spring. We defined a User
bean called admin
(the bean name is by default the bean method name). Spring beans are explained in the next chapter.
In the Main
class, we created a Spring context object from the AppConfig
class and retrieved the admin
bean from it. We used the bean and finally, closed the Spring context.