-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
SPRING COOKBOOK
By :
In this recipe, we will build a standard Java application (not a web application) using Spring. We will:
User classUser singleton in the Spring configuration classUser singleton in the main() methodIn this section, we will cover the steps to use Spring in a standard (not web) Java application.
com.springcookbook. For the Artifact Id field, enter springapp. Click on Finish.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>com.springcookbook.config Java package; in the left-hand side pane Package Explorer, right-click on the project and select New | Package….com.springcookbook.config package, create the AppConfig 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;
}com.springcookbook.main package with the Main class containing the main() method:package com.springcookbook.main;
public class Main {
public static void main(String[] args) {
}
}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.
Change the font size
Change margin width
Change background colour