Spring java based configuration @Import example
In the previous example we have
seen how to load multiple xml based configuration files. Spring 3 provides an alternative solution to move xml based configurations to java
based configurations.
This page talks about how to load multiple java based configurations in the spring. We can achieve this by using @Import annotation.
Here is a simple bean which handles all jdbc related services:
package com.java2novice.bean;
public class MyJdbcService {
public void createJdbcConnection(){
System.out.println("Creating jdbc connections...");
}
}
|
Here is a simple bean which handles business related services:
package com.java2novice.bean;
public class MyBusinessService {
public void runMyBusiness(){
System.out.println("Running business...");
}
}
|
Here is the java based configuration file to handle jdbc related beans:
package com.java2novice.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.java2novice.bean.MyJdbcService;
@Configuration
public class JdbcConfig {
@Bean(name="jdbcService")
public MyJdbcService getJdbcService(){
return new MyJdbcService();
}
}
|
Here is the java based configuration file to handle business related services:
package com.java2novice.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.java2novice.bean.MyBusinessService;
@Configuration
public class businessConfig {
@Bean(name="bussService")
public MyBusinessService getBusinessService(){
return new MyBusinessService();
}
}
|
Finally, the main configuration file which loads above shown configurations using @Import annotation:
package com.java2novice.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import({JdbcConfig.class, businessConfig.class})
public class MyAppConfig {
}
|
Here is the demo class:
package com.java2novice.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.java2novice.bean.MyBusinessService;
import com.java2novice.bean.MyJdbcService;
import com.java2novice.config.MyAppConfig;
public class SpringDemo {
public static void main(String a[]){
@SuppressWarnings("resource")
ApplicationContext context =
new AnnotationConfigApplicationContext(MyAppConfig.class);
MyJdbcService jdbc = (MyJdbcService) context.getBean("jdbcService");
jdbc.createJdbcConnection();
MyBusinessService busServ = (MyBusinessService) context.getBean("bussService");
busServ.runMyBusiness();
}
}
|
|