Spring Framework - Annotation

Enable Annotation Configuration for all Spring Beans

   <context:annotation-config/>

Spring Aotowired with Annotation

Spring Aotowired with Annotation by Type

Spring autowired or @Inject - Allow auto wired Spring property

public class UserService {

  @Autowired  // Autowire constructor
  public UserService (UserData data) {
     ...
  }

  @Autowired
  private String val;

  @Autowired
  public void setUserData(UserData userData) {
      this.userData = userData;
  }

  @Autowired
  public void setUserContacts(Map<String, String> contacts) {
      ...
  }

Autowire by type with a qualifier to distinct beans of the same type

public class UserService {
  @Autowired
  @Qualifier("main")
  private UserData userData;

}

  <bean class="com.innotrekker.app.UserData">
      <qualifier value="main"/>
  </bean>

Custom Qualifier

@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface CustomerType {
  String value();
}


public class UserService {
  @Autowired
  @CustomerType("VIP")
  private User user;
  ...
}

<bean class="com.innotrekker.app.User">
      <qualifier type="CustomerType" value="VIP"/>
</bean>

Spring Aotowired with Annotation by Name

Dependency Injection by name using Spring annotation

public class UserService {

  @Resource(name="someBeanId")
  public void setUserData(UserData data) {
      ...
  }

}

  • If no name is supplied in @Resource, use the field name

Spring Annotation

Spring Required - Bean property must be populated at configuration time

@Required
  public void setUserData(UserData userData) {
      this.userData = userData;
  }

Initialize and destroy method

public class UserService {

  @PostConstruct
  public void init() {
     ...
  }

  @PreDestroy
  public void destroy() {
     ...
  }
}

Auto Bean Detection

Enable Bean Detection by Annotation

<context:component-scan base-package="com.innotrekker.app"/>

Filter what can be auto detected

<beans>

   <context:component-scan base-package="com.innotrekker.app">
      <context:include-filter type="regex" expression=".*Stub.*Repository"/>
      <context:exclude-filter type="annotation"
                              expression="org.springframework.stereotype.Service"/>
   </context:component-scan>

</beans>

Define Auto Detected Beans

@Service
public class UserService {
   ...
}

Define a Spring Bean Id

@Service("myIdName")
public class UserService {
   ...
}
@Repository
public class User {
   ...
}

Define Spring Bean Scope using Annotation

@Service
@Scope("prototype")
public class UserService {
   ...
}

Java-based Container Configuration

Using Java standard @Configuration

@Configuration
public class AppConfig {
  @Bean   // Behave the same as <bean>
  public UserService userService() {
      return new UserServiceImpl();
  }
}

XML Equivalent (@Bean behaves as <bean>)

<beans>
  <bean id="userService" class="com.innotrekker.app.UserServiceImpl"/>
</beans> 

Initialize and destroy method of a Spring Bean using @Bean

@Configuration
public class AppConfig {
  @Bean(initMethod = "init")
  public User user() {
      return new User();
  }
  @Bean(destroyMethod = "destroy")
  @Scope("prototype")
  public Account account() {
      return new Account();
  }
}

Spring Bean Definition

  @Bean(name = "myBeanId")
  @Scope("prototype")
  public Account account() {
      return new Account();
  }

Import Spring Configuration

@Configuration
public class Config1 {
  public @Bean A a() { return new A(); }
}

@Configuration
@Import(Config1.class)
public class Config2 {
  public @Bean B b() { return new B(); }
}
// Automatic include Config1
ApplicationContext ctx = new AnnotationConfigApplicationContext(Config2.class);

Auto Scanning

Auto scanning for component annotation

<beans>
  <context:component-scan base-package="com.innotrekker"/>
</beans>
  AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
  ctx.scan("com.innotrekker");
  ctx.refresh();
@Configuration
public class ServiceConfig {
  private @Autowired UserService userService;

  public @Bean AccountService accountService() {
      ...
  }
}

@Configuration
public class RepositoryConfig {
  private @Autowired UserDao userDao;

  public @Bean AccountDao accountDao() {
      ...
  }
}

@Configuration
@Import({ServiceConfig.class, RepositoryConfig.class})
public class TestConfig {
    ...
}

public static void main(String[] args) {
  ApplicationContext ctx = new AnnotationConfigApplicationContext(TestConfig.class);
  UserService userService = ctx.getBean(UserService.class);

}

Spring Validation

public class UserValidator implements Validator {

    public boolean supports(Class c) {
        return User.class.equals(c);
    }

    public void validate(Object obj, Errors e) {
        ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
        User p = (User) obj;
        if (p.getAge() < 0) {
            e.rejectValue("age", "cannot_negative");
        }  
    }
}