本文介绍了利用注解配置Spring容器的方法,分享给大家,具体如下:
@Configuration标注在类上,相当于将该类作为spring的xml的标签
?
|
1
2
3
4
5
6
|
@Configuration
public class SpringConfiguration {
public SpringConfiguration() {
System.out.println("初始化Spring容器");
}
}
|
主函数进行测试
?
|
1
2
3
4
5
6
|
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实例
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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 ...");
}
}
|
?
|
1
2
3
4
5
6
7
8
9
10
11
12
|
@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注解
?
|
1
2
3
4
5
6
7
8
|
@Component
public class Cat {
public Cat() {
}
public void say() {
System.out.println("I am a cat" );
}
}
|
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@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扫描包配置路径
运行结果如下
?
|
1
2
3
4
|
初始化Spring容器
初始化User...
Hello,my name is tom,I am 20 years old
I am a cat
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。
原文链接:http://blog.csdn.net/JavaMoo/article/details/78758239
相关文章
猜你喜欢
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-27 26
-
2025-06-04 28
-
2025-05-29 20
-
2025-05-25 48
-
2025-05-29 19
热门评论

