• About

Luke's Tech Show

~ Knowledge is useless when not shared with others.

Luke's Tech Show

Tag Archives: Annotation

@Autowired Annotation in Spring

11 Tuesday Jun 2013

Posted by Luke Tong in Spring CORE

≈ 1 Comment

Tags

Annotation, Bean, Configuration file, Spring Framework, XML

In this post I will cover the @Autowired annotation introduced in Spring 2.5.

Three types of @Autowired

The @Autowired annotation can be applied to

  1. On setter methods
  2. On Properties
  3. On Constructors

Beforehand

Do we need a Spring bean configuration file?

The answer is yes and no.

For yes, we do need an xml file.

For no, we do not need to put all bean definitions in this xml file. Just put one line instead (suppose all beans in this sample are located under the com.foo.skill folder)

<context:component-scan base-package=”com.foo.skill” />

This will ask the system to find and register all beans in the application context.

Define our beans (make sure all the beans are located under com.foo.skill)

@Component
public class MyService {
public void printme(){
System.out.println(“printme”);
}
}

Through the annotation @Component, we’ve registered the bean MyService into the application context.

In the “Three types of @Autowired” section we have already known we can put @Autowired in three different places, in the following steps we will demonstrate how to use those three types of @Autowired annotations.

1. field

@Component
public class ExampleService {
@Autowired
private MyService myservice;

public MyService getMyservice() {
return myservice;
}

public String getMessage() {
return “Hello world!”;
}

}

2.setter

@Component
public class ExampleService {
private MyService myservice;

public MyService getMyservice() {
return myservice;
}

@Autowired

public void setMyservice() {
this.myservice=myservice;
}

public String getMessage() {
return “Hello world!”;
}

}

3.constructor

@Component
public class ExampleService {
private MyService final myservice;

@Autowired

ExampleService( MyService service){

super();

myservice=service;

}

public MyService getMyservice() {
return myservice;
}

public String getMessage() {

return “Hello world!”;
}

}

Test it by using SpringJUit4ClassRunner

@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class ExampleConfigurationTests {
@Autowired
private ExampleService service;
@Test
public void testSimpleProperties() throws Exception {
assertNotNull(service);
service.getMyservice().printme();
}
}

Note:

Please be noted, Constructor injection allows you to set the filed to final.

@Autowired on setter is preferable because lack of a setter makes mocking/unit testing more difficult.

Summary 

In this post we saw how to configure the Spring container using the @Autowired annotation. This annotation can be used for on setter methods, on fields, on constructors, with arguments. Examples for the same has been demonstrated.

Advertisements

Java config based Spring MVC

21 Tuesday May 2013

Posted by Luke Tong in RESTful, Spring MVC

≈ 1 Comment

Tags

Annotation, Configuration file, JSON, Spring Framework

Spring JavaConfig introduces a means of configuring the Spring Container using pure-java, i.e., without XML. I believe through the Java Config approach we got a better control on creation and initialization of beans. https://github.com/mrtong/FlightReservation.git contains all the code we will discuss in the rest of the post.
How to replace the applicationContext.xml?
Usually we put bean definitions in this file. A bean definition looks like:
<bean id=”flightDao” class=”com.foo.FlightDaoImpl”/>
Now things have changed we can do it in this way:
1. We define a class with @Configuration annotation which tells the system this is a kind of applicationContext.xml class.
2. Use the @Bean annotation to define a bean
Below is a sample

@Configuration
@EnableTransactionManagement
public class DefaultDaoConfig implements DaoConfig, TransactionManagementConfigurer, InitializingBean {

@Bean
@Override
public FlightDao getFlightDao() {
return new FlightDaoImpl(getSessionFactory());
}

}

We need to register those configure files in the system

In web.xml we have the following section

<servlet>
<servlet-name>springExample</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>

<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.foo.flight.web.WebConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

This tells Spring WebConfig is the entry point for all the config files.

In the WebConfig.java we have:

@EnableWebMvc
@Configuration
@Import({ ControllerConfig.class, DefaultServiceConfig.class, DefaultDaoConfig.class })
public class WebConfig extends WebMvcConfigurerAdapter {

…….

}

As you may have known, in Spring, we have two kinds of transaction, one is declarative the other one the programmatic. I do not want to write any code regarding transaction thus in this sample we use the declarative mode.

How to add transactions in your Spring code?

The @EnableTransactionManagement annotation (which I mentioned in code snippet 1) enables Spring’s annotation driven transaction management capabilities for services annotated with @Transactional.

You can find the following code snippet in the ReservationServiceImpl.java

@Transactional(rollbackFor = { NoSeatAvailableException.class }, readOnly=false)
public Ticket bookFlight(Reservation booking) throws NoSeatAvailableException {
…
}

It is quite to implement REST in the Spring Framework. The following snippet can be found in ReservationController.java file.  The getReservations returns an XML or JSON representation of the reservations.

@RequestMapping(value = “/reservations”, method = RequestMethod.GET, produces = {
MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
@ResponseBody
public Reservations getReservations() {
return new Reservations(reservationService.getReservations());
}

A known bug within Maven. 

When I tried to integrate everything into a war file and put it into my Tomcat server, it raised the following exception.

NoSuchMethodError: javax.servlet.jsp.JspFactory.getJspApplicationContext(Ljavax/servlet/ServletContext;)Ljavax/servlet/jsp/JspApplicationContext;

Oooooops! After investigating, I found there must be some conflict between jsp-api-2.0.jar and Tomcat(I tried it later in JBoss 5.0, unfortunately, it has this problem as well). Furthermore I do not know why this jar file was automatically added into my war file! The temp solution is, removing that jar file every time you do the deployment. Or, which is my approach, adding the following into pom.xml

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>

Done!

===

Summary, in this post I demonstrated the Java Config feature of Spring. The whole code can be found in my git which is  https://github.com/mrtong/FlightReservation.git

context:annotation-config vs context:component-scan

24 Wednesday Apr 2013

Posted by Luke Tong in Spring MVC

≈ Leave a comment

Tags

Annotation, Java, Spring Framework, XML

A few days ago I saw a question in stackoverflow(http://bit.ly/11k6hp1) asking the difference between <context:annotation-config> and <context:component-scan> in Spring MVC 3.0. I think this will be asked in technical interviews against your Spring skills.

The answer is

<context:annotation-config> is used to activate annotations in beans already registered in the application context (no matter if they were defined with XML or by package scanning).

<context:component-scan> can also do what <context:annotation-config> does but <context:component-scan> also scans packages to find and register beans within the application context.

I found this nice summary of which annotations are picked up by which declarations (http://bit.ly/Y3RWAt).

By studying it you will find that <context:component-scan/> recognizes a super-set of annotations recognized by <context:annotation-config/>, namely:

@Component, @Service, @Repository, @Controller, @Endpoint, @Configuration, @Bean, @Lazy, @Scope, @Order, @Primary, @Profile, @DependsOn, @Import, @ImportResource
As you can see <context:component-scan/> logically extends <context:annotation-config/> with CLASSPATH component scanning and Java @Configuration features

Advertisements

Subscribe

  • Entries (RSS)
  • Comments (RSS)

Archives

  • October 2018
  • September 2018
  • February 2018
  • January 2018
  • October 2017
  • July 2017
  • June 2017
  • April 2017
  • March 2017
  • February 2017
  • January 2017
  • December 2016
  • December 2013
  • September 2013
  • August 2013
  • July 2013
  • June 2013
  • May 2013
  • April 2013

Categories

  • Agile
  • Algorithm
  • Cloud
  • IT Misc
  • Java
    • Web Service
      • RESTful
  • Java8
  • JavaScript
    • jQuery
  • JBoss
  • JPA
  • Linux
  • MQ
  • Spring CORE
  • Spring MVC
  • TDD
  • Uncategorized

Meta

  • Register
  • Log in

Blog at WordPress.com.

Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy