未分类
2020-12-08 11:37:02
1822677238@qq.com
手机扫码查看
2020java框架教程之spring概述以及入门helloworld
什么是spring?
Spring是一个非常活跃的开源框架,由Rod Johnson开发,帮助分离项目组件之间的依赖关系,它的主要目的是简化企业开发
核心概念
IOC:Inversion Of Control控制反转
DI:Dependency Injection 依赖注入
AOP:Aspect Oriented Programming 面向切面编程
Spring的组成

使用注解配置bean对象
@Repository
public class MessageService {
public MessageService() {
System.out.println("MessageService...");
}
//执行打印功能,返回要打印的字符串
public String getMessage(){
return "Hello World";
}
}
使用自动装配
@Repository
public class MessagePrinter {
public MessagePrinter() {
System.out.println("MessagePrinter...");
}
//建立和 MessageService的关系
private MessageService ms;
//设置 ms 的值
@Autowired
public void setMs(MessageService ms) {
this.ms = ms;
}
public void printMessage(){
System.out.println(this.ms.getMessage());
}
}
使用注解扫描
@ComponentScan
public class ApplicationSpring {
public static void main(String[] args) {
System.out.println("applicationSpring");
ApplicationContext context;
//初始化 spring 容器
context=new AnnotationConfigApplicationContext(ApplicationSpring.class);
//从容器获取 MessagePrinter 对象
MessagePrinter mp = context.getBean(MessagePrinter.class);
//从容器获取 MessageService 对象
MessageService ms = context.getBean(MessageService.class);
System.out.println(ms.getMessage());
}
}
使用XML文件配置

利用ClassPathXmlApplicationContext读取配置文件

加载配置文件




发表回复