这篇文章给大家分享的是有关如何使用注解配置Spring容器的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

成都创新互联公司是专业的白沙黎族网站建设公司,白沙黎族接单;提供做网站、网站设计,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行白沙黎族网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!
具体如下:
@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
感谢各位的阅读!关于“如何使用注解配置Spring容器”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
网站栏目:如何使用注解配置Spring容器
文章位置:http://www.jxjierui.cn/article/jcphcg.html


咨询
建站咨询
