本文介绍了利用注解配置Spring容器的方法,分享给大家,具体如下:
@Configuration标注在类上,相当于将该类作为spring的xml的标签
@Configuration public class SpringConfiguration { public SpringConfiguration() { System.out.println("初始化Spring容器"); } }
主函数进行测试
public class Main { public static void main(String[] args) { ApplicationContext cOntext= new AnnotationConfigApplicationContext(SpringConfiguration.class); } }
利用注解AnnotationConfigApplicationContext加载ApplicationContext
运行结果如下
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2e5d6d97: startup date [Sat Dec 09 11:29:51 CST 2017]; root of context hierarchy
初始化Spring容器
利用@Bean向容器中添加bean实例
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("初始化User..."); } public void say() { System.out.println(String.format("Hello,my name is %s,I am %d years old ", username, age)); } public void destory(){ System.out.println("销毁User ..."); } }
@Configuration public class SpringConfiguration { public SpringConfiguration() { System.out.println("初始化Spring容器"); } //@Bean注解注册bean,同时制定初始化和销毁的方法 @Bean(name = "user", initMethod = "init", destroyMethod = "destory") @Scope("prototype") public User getUser() { return new User("tom", 20); } }
@Bean注解在返回实例的方法上,如果没有指定bean的名字,则默认与标注的方法名称相同
@Bean注解默认作用域为单例的Singleton作用域
利用@ComponentScan添加自动扫描@Service,@Ripository,@Controller,@Component注解
@Component public class Cat { public Cat() { } public void say() { System.out.println("I am a cat" ); } }
@Configuration @ComponentScan(basePackages = "com.spring.annotation.ioc") public class SpringConfiguration { public SpringConfiguration() { System.out.println("初始化Spring容器"); } //@Bean注解注册bean,同时制定初始化和销毁的方法 @Bean(name = "user", initMethod = "init", destroyMethod = "destory") @Scope("prototype") public User getUser() { return new User("tom", 20); } }
利用basePackages扫描包配置路径
运行结果如下
初始化Spring容器 初始化User... Hello,my name is tom,I am 20 years old I am a cat
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。