Starting from 4.2, Spring annotations can be processed when used on Java 8 default methods as well. This allows for a lot of flexibility in creating complex bean implementations and configuration classes (the class with @Configuration). We can even take the advantage of Java 8 default method's multiple inheritance behavior pattern.
Let's see how to use Spring annotations on Java 8 default methods.
Example
An interface for bean
package com.logicbig.example;
import javax.annotation.PostConstruct;
public interface IMyBean {
@PostConstruct
default void init() {
System.out.println("post construct: "+this.getClass().getSimpleName());
}
}
The implementation
package com.logicbig.example;
public class MyBean implements IMyBean {
public void showMessage(String msg) {
System.out.println(msg);
}
}
An interface for configuration
package com.logicbig.example;
import org.springframework.context.annotation.Bean;
public interface IMyConfig {
@Bean
default MyBean myBean() {
return new MyBean();
}
}
The implementation
package com.logicbig.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfig implements IMyConfig {
public static void main(String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(MyConfig.class);
MyBean bean = context.getBean(MyBean.class);
bean.showMessage("a test message");
}
}
Outputpost construct: MyBean a test message
The older version say 4.1.9.RELEASE will end up in the following exception:
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.logicbig.example.MyBean] is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:371)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:331)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:975)
at com.logicbig.example.MyConfig.main(MyConfig.java:13)
Example ProjectDependencies and Technologies Used: - spring-context 4.2.0.RELEASE: Spring Context.
- JDK 1.8
- Maven 3.3.9
|