This article introduces the method of configuring Spring containers using annotations. I will share it with you. The details are as follows:
@Configuration annotated on the class is equivalent to using the class as the tag of spring's xml
@Configurationpublic class SpringConfiguration { public SpringConfiguration() { System.out.println("Initialize Spring Container"); }}Main function for testing
public class Main { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class); }}Load ApplicationContext using the annotationAnnotationConfigApplicationContext
The operation results are as follows
Information: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2e5d6d97: startup date [Sat Dec 09 11:29:51 CST 2017]; root of context hierarchy
Initialize Spring container
Use @Bean to add bean instance to container
public class User { private String username; private int age; public User(String username, int age) { this.username = username; this.age = age; } public void init(){ System.out.println("Initialize User..."); } public void says() { System.out.println(String.format("Hello,my name is %s,I am %d years old ", username, age)); } public void destory(){ System.out.println("Destroy User..."); }} @Configurationpublic class SpringConfiguration { public SpringConfiguration() { System.out.println("Initialize Spring Container"); } //@Bean annotation to register beans, and at the same time formulate methods for initialization and destruction @Bean(name = "user", initMethod = "init", destroyMethod = "destory") @Scope("prototype") public User getUser() { return new User("tom", 20); }} @Bean annotation is on the method that returns the instance. If the bean name is not specified, the default is the same as the method name of the annotated one.
@Bean annotation default scope is Singleton scope of singleton
Use @ComponentScan to add automatic scanning @Service,@Ritory,@Controller,@Component annotation
@Componentpublic class Cat { public Cat() { } public void says() { System.out.println("I am a cat" ); }} @Configuration@ComponentScan(basePackages = "com.spring.annotation.ioc")public class SpringConfiguration { public SpringConfiguration() { System.out.println("Initialize Spring Container"); } //@Bean annotation to register beans, and at the same time formulate methods for initialization and destruction @Bean(name = "user", initMethod = "init", destroyMethod = "destory") @Scope("prototype") public User getUser() { return new User("tom", 20); }}Use basePackages to scan packages to configure paths
The operation results are as follows
Initialize Spring container Initialize User...Hello,my name is tom,I am 20 years old I am a cat
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.