Spring DI
Configuration
In the Spring framework, a configuration file called Configuration is passed to the DI container, and "Return this instance in such a case" is set. There are three types of Configuration files.
--Java-based Configuration --XML-based Configuration --Annotation-based Configuration
The annotation-based Configuration is described below.
@Configuration Indicates that it is a Configuration class.
AppConfig
package com.example;
@Configuration
public class AppConfig {
}
@Component Register the class as a bean to be managed by the DI container.
User
package com.example;
@Component
public class User {
public String getName(){
...
}
}
@ComponentScan Scan the class with @Component and register it in DI as a bean. The scan target can be specified as a package. The settings for the AppConfig class mentioned earlier are as follows.
Configuration
package com.example;
@Configuration
@ComponentScan("com.example")
public class AppConfig {
}
If you use the DI container with the above annotations, the code will be as follows.
DemoIoC
package com.example;
public class DemoIoC {
public static void main(String args[]){
//Build a DI container and pass a Configuration file
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
//Get Bean
User user = context.getBean(User.class);
System.out.println(User.getName())
}
}
In Spring framework, Configuration can be grouped and managed as a profile. For example, Configuration for development, Configuration for testing, and Configuration for products can be managed separately, and the Configuration can be easily switched.
@Profile Set the profile. Change the User class hierarchy as follows and set the profile.
User
package com.example;
public interface User {
public String getName();
}
UserDummy
package com.example;
@Component
@Profile("dev") //Set profile with the name dev
public class UserDummy implements User {
...
}
UserMaster
package com.example;
@Component
@Profile("test") //Set profile with the name test
public class UserImpl implements User {
...
}
Let's set a profile and use the above User class hierarchy.
DemoIoC
package com.example;
public class DemoIoC {
public static void main(String args[]){
//Build DI container
//Set dev as profile
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
context.register(AppConfig.class);
context.getEnvironment().addActiveProfile("dev");
context.refresh();
//Get Bean
//The implementation of user is UserDummy
User user = context.getBean(User.class);
System.out.println(User.getName())
}
}
Recommended Posts