I am using the annotation validation as below:
public String processRegistration(#Valid Spitter spitter, Errors errors,
Model model) {
if (errors.hasErrors()) {
return "registerForm";
}
...
}
But the errors.hasErrors() always return false. I guess I didn't turn on some kind of switch for the annotation driven validation. But how can I do it with JavaConfig in Spring 4? I tried to apply the #AnnotationDrivenConfig to the configuration class, but that type cannot even be resolved.
ADD 1
I already have the following configuration in the servlet-context.xml, but still doesn't work.
<annotation-driven />
ADD 2
The spitter.java:
package com.learnspring.mvc.web;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.hibernate.validator.constraints.Email;
public class Spitter {
private Long id;
#NotNull
#Size(min = 5, max = 16)
private String username="default name";
#NotNull
#Size(min = 5, max = 25)
private String password;
#NotNull
#Size(min = 2, max = 30)
private String firstName;
#NotNull
#Size(min = 2, max = 30)
private String lastName;
#NotNull
#Email
private String email;
public Spitter() {
}
public Spitter(String username, String password, String firstName,
String lastName, String email) {
this(null, username, password, firstName, lastName, email);
}
public Spitter(Long id, String username, String password, String firstName,
String lastName, String email) {
this.id = id;
this.username = username;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that, "firstName",
"lastName", "username", "password", "email");
}
#Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this, "firstName",
"lastName", "username", "password", "email");
}
}
The SpitterController.java
package com.learnspring.mvc.web;
import static org.springframework.web.bind.annotation.RequestMethod.*;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.learnspring.mvc.web.Spitter;
import com.learnspring.mvc.web.SpitterRepository;
#Controller
#RequestMapping("/spitter")
public class SpitterController {
private SpitterRepository spitterRepository;
#Autowired
public SpitterController(SpitterRepository spitterRepository) {
this.spitterRepository = spitterRepository;
}
#RequestMapping(value = "/register", method = GET)
public String showRegistrationForm(Model model) {
model.addAttribute("spitter", new Spitter());
return "registerForm";
}
#RequestMapping(value = "/register", method = POST)
public String processRegistration(#Valid Spitter spitter,
Errors errors, Model model) {
if (errors.hasErrors()) {
return "registerForm";
}
if (spitter == null) {
model.addAttribute("ufo", "spitter is null!");
model.addAttribute("mark", "MARKER");
return "forward:/spitter/spitter/registerFail";
}
else if (!spitter.getUsername().contains("ufo")) {
model.addAttribute("ufo", "spitter user name is not ufo!!");
model.addAttribute("mark", "MARKER:" + spitter.getUsername());
model.addAttribute("pwd", "MARKER:" + spitter.getPassword());
return "forward:/spitter/spitter/registerFail";
}
else
return "redirect:/spitter/spitter/registerOK";
}
#RequestMapping(value = "/{username}", method = GET)
public String showSpitterProfile(#PathVariable String username, Model model) {
Spitter spitter = spitterRepository.findByUsername(username);
model.addAttribute(spitter);
return "profile";
}
#RequestMapping(value = "/spitter/registerOK", method = GET)
public String showRegisterOK() {
return "registerOK";
}
#RequestMapping(value = "/spitter/registerFail", method = POST)
public String showRegisterFail() {
return "registerFail";
}
}
The registerForm.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="f" %>
<%# page session="false" %>
<html>
<head>
<title>Spitter</title>
<link rel="stylesheet" type="text/css"
href="<c:url value="/resources/style.css" />" >
</head>
<body>
<h1>Register</h1>
<f:form method="POST" commandName="spitter">
f:First Name: <f:input path="firstName" /><br/>
f-Last Name: <f:input path="lastName" /><br/>
f-Email: <f:input path="email" /><br/>
f-User Name: <f:input path="username" /><br/>
f-Password: <f:input path="password" /><br/>
<input type="submit" value="Register" />
</f:form>
</body>
</html>
The WebConfig.java:
package com.learnspring.mvc.web;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("com.learnspring.mvc.web")
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
super.addResourceHandlers(registry);
}
}
The RootConfig.java
package com.learnspring.mvc.config;
import java.util.regex.Pattern;
import com.learnspring.mvc.config.RootConfig.WebPackage;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.Import;
import org.springframework.core.type.filter.RegexPatternTypeFilter;
#Configuration
#ComponentScan(basePackages = { "com.learnspring.mvc" }, excludeFilters = { #Filter(type = FilterType.CUSTOM, value = WebPackage.class) })
public class RootConfig {
public static class WebPackage extends RegexPatternTypeFilter {
public WebPackage() {
super(Pattern.compile("com.learnspring.mvc\\.web"));
}
}
}
The SpitterWebInitialization.java
package com.learnspring.mvc.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.learnspring.mvc.config.RootConfig;
import com.learnspring.mvc.web.WebConfig;
public class SpitterWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
ADD 3
And the web.xml: (Actually, everything is commented out.)
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<!--
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
-->
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<!--
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
-->
<!-- Processes application requests -->
<!--
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
-->
</web-app>
Judging from your explanation and the following error java.lang.ClassNotFoundException: javax.validation.Validator Spring doesn't see the classes and as such doesn't enable JSF-303 validation.
Make sure that the correct jars are on the classpath and that you have an implementation as well. When using maven adding something like the following should do the trick.
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
This will add the needed jars to the WEB-INF/lib directory which in turn lets Spring Web MVC detect it and configure the appropriate bean.
For an explanations of the different annotations you might want to check In Hibernate Validator 4.1+, what is the difference between #NotNull, #NotEmpty, and #NotBlank?.
I see two points in your code that may cause de problem.
1) Instead of <annotation-driven /> use the correct namespace <mvc:annotation-driven/>.
2) On your #Controller change your functions parameters from:
public String processRegistration(#Valid Spitter spitter, Errors errors,
Model model) {
if (errors.hasErrors()) {
return "registerForm";
}
...
To:
public String processRegistration(#ModelAttribute("spitter") #Valid Spitter spitter, BindingResult result) {
if (result.hasErrors()) {
return "registerForm";
}
...
Try it! ;)
Related
I am trying read a CSV file using spring batch . I am using FlatFileItemReader. Batch execution is chunk based.
But the issue is CSV format is not fixed in each batch execution cycle.
For example ,
In 1st Cycle- Let's say I have a CSV which has header as id, firstName, LastName.
In 2nd Cycle - It can have header as name, address, salary.
I want to save data for csv in Key-Value pair in one column.(For each row in CSV ,a row will be saved in DB.)
How to implement reader,processer,writer for this?
Reader Class for fixed format i have implemented as below:
public class Reader {
public static FlatFileItemReader<Customer> reader(String path) {
FlatFileItemReader<Customer> reader = new FlatFileItemReader<Customer>();
reader.setResource(new ClassPathResource(path));
reader.setLineMapper(new DefaultLineMapper<Customer>() {
{
setLineTokenizer(new DelimitedLineTokenizer() {
{
setNames(new String[] { "id", "firstName", "lastName" });
}
});
setFieldSetMapper(new BeanWrapperFieldSetMapper<Customer>() {
{
setTargetType(Customer.class);
}
});
}
});
return reader;
}
}
For Writer
public class Writer implements ItemWriter<Customer> {
private final CustomerDao customerDao;
public Writer(CustomerDao customerDao) {
this.customerDao = customerDao;
}
#Override
public void write(List<? extends Customer> customers) throws Exception {
customerDao.insert(customers);
}
}
For BatchCOnfig
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.javasampleapproach.batchcsvpostgresql.dao.CustomerDao;
import com.javasampleapproach.batchcsvpostgresql.model.Customer;
import com.javasampleapproach.batchcsvpostgresql.step.Listener;
import com.javasampleapproach.batchcsvpostgresql.step.Processor;
import com.javasampleapproach.batchcsvpostgresql.step.Reader;
import com.javasampleapproach.batchcsvpostgresql.step.Writer;
#Configuration
#EnableBatchProcessing
public class BatchConfig {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Autowired
public CustomerDao customerDao;
#Bean
public Job job() {
return jobBuilderFactory.get("job").incrementer(new RunIdIncrementer()).listener(new Listener(customerDao))
.flow(step1()).end().build();
}
#Bean
public Step step1() {
return stepBuilderFactory.get("step1").<Customer, Customer>chunk(2)
.reader(Reader.reader("customer-data.csv"))
.processor(new Processor()).writer(new Writer(customerDao)).build();
}
}
Customer DTO is as below
public class Customer {
private long id;
private String firstName;
private String lastName;
public Customer() {
}
public Customer(long id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Spring Batch - Is it possible to have a dynamic column in FlatFileReader?
This question is similar to my question but i am unable to understand the answer.
I am new to Java using STS 4 Eclipse, Java 8.
I am trying to use JSTL tags to output some values through my jsp file, however, I am not getting any output from my forEach loop in list.jsp. I am getting an output from the < p > tag directly before the loop.
Sorry for the large amount of code just didn't want to miss anything.
list.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Channels</title>
</head>
<body>
<p>Channels</p>
<c:forEach items="${channels}" var="channel">
<p>${channel.name}'s topic is ${channel.topic}</p>
<p> Link to the channel</p>
</c:forEach>
</body>
</html>
ChannelController.java
package co2103.hw1.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import co2103.hw1.Hw1Application;
import co2103.hw1.domain.Channel;
#Controller
public class ChannelController {
public List<Channel> channels;
#GetMapping("/channels")
public String channelsList(Model model) {
model.addAttribute("channels", Hw1Application.channels);
return "channels/list";
}
#RequestMapping("/newChannel")
public String newchannel(Model model) {
model.addAttribute("channel", new Channel());
return "channels/form";
}
#PostMapping("/addChannel")
public String updateChannel(#ModelAttribute Channel channel, BindingResult result) {
if (result.hasErrors()) {
return "channels/form";
}
int id = 0;
channel.setId(id);
String name = null;
channel.setName(name);
String topic = null;
channel.setTopic(topic);
Hw1Application.channels.add(channel);
return "redirect:/";
}
}
Hw1Application
package co2103.hw1;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import co2103.hw1.domain.Channel;
import co2103.hw1.domain.Show;
#SpringBootApplication
public class Hw1Application {
public static void main(String[] args) {
SpringApplication.run(Hw1Application.class, args);
}
public static List<Channel> channels = new ArrayList<>();
public static List<Show> shows = new ArrayList<>();
public void run(String... args) {
Channel channel = new Channel();
channel.setId(0);
channel.setName("Channel 1");
channel.setTopic("Nothing");
Show show = new Show();
show.setTitle("Show 1");
show.setProducer("Me");
show.setCategory("News");
show.setEpisodes(300);
Show show2 = new Show();
show.setTitle("Show 2");
show.setProducer("Me2");
show.setCategory("News2");
show.setEpisodes(300);
shows.add(show);
shows.add(show2);
channel.setShows(shows);
}
}
Channel.java
package co2103.hw1.domain;
import java.util.List;
public class Channel {
private int id;
private String name;
private String topic;
private List<Show> shows;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public List<Show> getShows() {
return shows;
}
public void setShows(List<Show> shows) {
this.shows = shows;
}
}
in the class Hw1Application ==> the method public void run(String... args) :
you need to add in the end
channels.add(channel)
Because in ChannelController.java you called channels ( that is empty in w1Application and not setted) in you #GettingMapping
So the answer that worked for me was to implements CommandLineRunner in my Hw1Application class
Hw1Application.java
#SpringBootApplication
public class Hw1Application implements CommandLineRunner {
....
}
Spring Boot version:2.1.3.RELEASE,Spring Framework version:5.1.5.RELEASE.
Simple xml config like this:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="CustomerBean" class="io.github.ctlove0523.Customer">
<property name="person">
<bean class="io.github.ctlove0523.Person">
<property name="name" value="stackoverflow" />
<property name="address" value="address1" />
<property name="age" value="15" />
</bean>
</property>
</bean>
</beans>
how the java config would like?
Person.java
import org.springframework.beans.factory.annotation.Value;
public class Person {
#Override
public String toString() {
return "Person [name=" + name + ", address=" + address + ", age=" + age + "]";
}
private String name;
private String address;
private Integer age;
public String getName() {
return name;
}
#Value("stackoverflow")
public void setName(String name) {
this.name = name;
}
#Value("address1")
public void setAddress(String address) {
this.address = address;
}
#Value("15")
public void setAge(Integer age) {
this.age = age;
}
}
CustomerBean.java
import org.springframework.beans.factory.annotation.Autowired;
public class CustomerBean {
Person person;
public Person getPerson() {
return person;
}
#Autowired
public void setPerson(Person person) {
this.person = person;
}
}
App.java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App
{
public static void main( String[] args )
{
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
context.registerShutdownHook();
CustomerBean customerBean = context.getBean(CustomerBean.class);
System.out.println(customerBean.getPerson());
}
}
AppConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
public class AppConfig {
#Bean
public CustomerBean customerBean() {
return new CustomerBean();
}
#Bean
public Person person() {
return new Person();
}
}
Output :
Person [name=stackoverflow, address=address1, age=15]
Edit: Is this what you are looking for ??
Create beans from inner class using spring
Check the Spring documentation on Java configuration : https://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html
Depending on the code of your Person class, it would look something like this :
import io.github.ctlove0523.Customer;
#Configuration
public class AppConfig {
#Bean
public Customer customerBean() {
Customer myBean = new Customer();
// constructor or setter methods for Person
return myBean;
}
}
I am testing FreeMarker
Maven dependencies:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
</dependencies>
Simple class User:
public class User {
private String firstName;
private String lastName;
private String email;
public User(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Simple FreeMarker file (basicJson.ftl):
Name: ${user.firstName} ${user.lastName}
Class for create a Configuration:
import java.io.File;
import java.io.IOException;
import freemarker.template.Configuration;
import freemarker.template.TemplateExceptionHandler;
public class FreemarkerConfigurationFactory {
public static Configuration newFreemarkerConfiguration() throws IOException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
cfg.setDirectoryForTemplateLoading(new File("./templates/tests/"));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
return cfg;
}
}
Test class:
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import javax.json.Json;
import javax.json.JsonObject;
import org.junit.Before;
import org.junit.Test;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class FreemarkerJsonTest {
private Configuration cfg;
private ByteArrayOutputStream output;
private Template template;
private Writer writer;
private Map<String, Object> map;
#Before
public void setUp() throws Exception {
cfg = FreemarkerConfigurationFactory.newFreemarkerConfiguration();
output = new ByteArrayOutputStream();
writer = new OutputStreamWriter(output);
map = new HashMap<>();
}
#Test
public void objectTest() throws Exception {
User user = new User("Clarice", "Leman", "clarice.leman#domain.com");
map.put("user", user);
String outputString = process("basicJson.ftl", map);
assertEquals("Name: Clarice Leman", outputString);
}
#Test
public void jsonTest() throws Exception {
JsonObject jsonUser = Json.createObjectBuilder()
.add("id", 10)
.add("firstName", "Clarice")
.add("lastName", "Leman")
.add("email", "clarice.leman#domain.com")
.build();
map.put("user", jsonUser);
String outputString = process("basicJson.ftl", map);
assertEquals("Name: Clarice Leman", outputString);
}
private String process(String templateName, Object root) throws Exception {
template = cfg.getTemplate(templateName);
template.process(root, writer);
return output.toString();
}
}
The question is that the test "objectTest()" passes but the test "jsonTest()" no, because it produces a String:
Name: "Clarice" "Leman"
Using a Online FreeMarker Template (http://freemarker-online.kenshoo.com/):
Template:
Name: ${user.firstName} ${user.lastName}
Data Model:
user = {"firstName":"Clarice","lastName":"Leman","email":"clarice.leman#domain.com"}
Result
Name: Clarice Leman
The JSON you enter on FreeMarker Online is transformed to List-s and Map-s by FreeMarker Online before passed to FreeMarker itself. The syntax of that whole box is specific to that online service. So if you have JSON to show, either it has to be converted to a something that the default ObjectWrapper of FreeMarker already understands, or the ObjectWrapper has to be extended to understand javax.json classes. (But often, you bind the JSON to some application-specific classes anyway, and those often already use JavaBeans conventions and List-s, which the default ObjectWrapper understands.)
I have defined in a xml config file:
<bean id="bootstrap" class="com.package.Bootstrap"></bean>
this works fine.
The bootsrap class :
public class Bootstrap {
#PostConstruct
public void onServerStart() {
System.out.println("PRINTSSSSSSSSSSSSSSSSSSS");
}
}
The method gets fired.
But how can I get rid of the xml part, and annotate bootstrap to be a bean instead?
I have
<mvc:annotation-driven />
<context:annotation-config />
and
<context:component-scan base-package="com.package" />
But I was wondering what the annotation used should be that replaces:
<bean id="bootstrap" class="com.package.Bootstrap"></bean>
I could not find anything about this online and in the spring docs :(
There's documentation regarding this; you'll want a stereotype annotation like #Component.
Stereotype bean annotations
this is a simple example that I have just made:
Main.java
package the.test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
public class Main {
public static void main(String[] args) {
AbstractApplicationContext aac = new AnnotationConfigApplicationContext(Person.class, Phones.class);
Person person = aac.getBean(Person.class);
System.out.println(person.getPhones().getPhoneOne());
System.out.println(person.getPhones().getPhoneTwo());
System.out.println(person.getSurname());
System.out.println(person.getName());
System.out.println(person.getAge());
aac.close();
}
}
Person.java
package the.test;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
#Configuration
//you may use #ComponentScan("the.test") here and omit declaring
//"Phone.class" in the main method
public class Person {
private int age;
private String name;
private String surname;
private Phones phones;
public int getAge() {
return age;
}
#Value("33")
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
#Value("John")
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
#Value("Due")
public void setSurname(String surname) {
this.surname = surname;
}
public Phones getPhones() {
return phones;
}
#Resource
public void setPhones(Phones phones) {
this.phones = phones;
}
}
Phones.java
package the.test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
#Configuration
public class Phones {
private String PhoneOne;
private String PhoneTwo;
public String getPhoneOne() {
return PhoneOne;
}
#Value("987654321")
public void setPhoneOne(String phoneOne) {
PhoneOne = phoneOne;
}
public String getPhoneTwo() {
return PhoneTwo;
}
#Value("123456")
public void setPhoneTwo(String phoneTwo) {
PhoneTwo = phoneTwo;
}
}
this is completely based on Spring Annotation and is made on spring framework 4.2.5
hope it helps.