1.创建
GroupId----项目目录(com.javaspring)
Artifactid---项目名称(spring01qiuckstart)
Version--版本默认
2.默认打开的pom.xml文件
编辑---编写spring核心项目依赖
4.0.0
com.springjava
spring01quickstart
1.0-SNAPSHOT
org.springframework
spring-context 核心
4.3.12.RELEASE 版本
---创建一个
MessageService-类
packagehello;/*** d打印服务
* 执行打印功能
* @Date: 2019/7/12 14:51
* @Version 1.0*/
public classMessageService {publicString getMessage(){return "Hello World";
}
}
---创建一个类MessagePrinter-用来调用 MessageService这个类,实现打印功能
---建立类和类的关联关系--一个类作为另一个类的成员变量
按alt和insert键--调用getset方法--快捷键
packagehello;/*** @Author: 建立和MessageService的关联关系
* @Date: 2019/7/12 15:07
* @Version 1.0*/
public classMessagePrinter {privateMessageService service;public voidsetService(MessageService service) {this.service =service;
}public voidprintMessage(){
System.out.println(this.service.getMessage());
}
}
--创建主类--调用打印机
-写一个main方法--打印一个调试信息--创建消息打印机对象--创建消息服务对象--设置打印机对象的service属性--打印消息
packagehello;/*** @Author:
* @Date: 2019/7/12 15:19
* @Version 1.0
* -写一个main方法--
* 打印一个调试信息--
* 创建消息打印机对象--
* 创建消息服务对象--
* 设置打印机对象的service属性
* --打印消息*/
public classApplicaton {public static voidmain(String[] args) {
System.out.println("application");
MessagePrinter messagePrinter= newMessagePrinter();
MessageService messageService= newMessageService();
messagePrinter.setService(messageService);
messagePrinter.printMessage();
}
}
---运行程序---在main方法上右键--run--
----在类上添加注解不再new
--此处可省略--自动生成--都有spring 来管理
----在MessageService中创建一个无参构造方法-方便打印输出--ctrl+o---选择object进行创建(或选择alt+inset--选overid)
----在printer 也创建一个无参构造
---创建另一个主类--applicationapring--
加入扫描注解--
@ComponentScan---扫描有commpontent注解的类---自动创建到spring容器当中
---将容器初始化---包含spring 类路径
packagehello;importorg.springframework.context.ApplicationContext;importorg.springframework.context.annotation.AnnotationConfigApplicationContext;importorg.springframework.context.annotation.ComponentScan;/*** @Author:
* @Date: 2019/7/12 15:19
* @Version 1.0
**/@ComponentScanpublic classApplicatonspring {public static voidmain(String[] args) {
System.out.println("application");/*MessagePrinter messagePrinter = new MessagePrinter();
MessageService messageService = new MessageService();
messagePrinter.setService(messageService);
messagePrinter.printMessage();*/ApplicationContext context= new AnnotationConfigApplicationContext(Applicatonspring.class);
MessagePrinter printer= context.getBean(MessagePrinter.class);
MessageService service= context.getBean(MessageService.class);
System.out.println(printer);
System.out.println(service);
}
}