Spring:入门程序
- 不使用spring和使用spring的区别
package com.wuzl;
import org.springframework.stereotype.Component;
/**
* 消息服务,打印输出
*/
@Component
public class MessageServices {
public MessageServices() {
super();
System.out.println("MessageService...");
}
/**
* 执行打印功能
* @return 返回打印字符
*/
public String getMessage(){
return "hello word!";
}
}
package com.wuzl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 打印机
*/
@Component
public class MessagePrint {
public MessagePrint() {
super();
System.out.println("MessagePrint...");
}
/**
* 建立和MessageService的关联关系
*/
private MessageServices service;
/**
* 设置service的值
* @param service
*/
@Autowired//@Autowired关联对象之间的关系
public void setService(MessageServices service) {
this.service = service;
}
public void printMessage(){
System.out.println(this.service.getMessage());
}
}
不使用spring创建对象
package com.wuzl;
/**
* 不使用spring创建对象
*/
public class Application {
public static void main(String[] args) {
System.out.println("打印");
/**
* 创建打印机对象
*/
MessagePrint print=new MessagePrint();
/**
* 创建消息服务对象
*/
MessageServices services=new MessageServices();
/**
* 设置打印机对象的service属性
*/
print.setService(services);
/**
* 打印消息
*/
print.printMessage();
}
}
使用spring创建对象和@Autowired注解关联对象之间的关系
package com.wuzl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
/**
* 使用spring创建对象
*/
@ComponentScan//Scan组件扫描
public class ApplicationSpring {
public static void main(String[] args) {
System.out.println("Spring打印");
// /**
// * 创建打印机对象
// */
// MessagePrint print=new MessagePrint();
//
// /**
// * 创建消息服务对象
// */
// MessageServices services=new MessageServices();
//
// /**
// * 设置打印机对象的service属性
// */
// print.setService(services);
// /**
// * 打印消息
// */
// print.printMessage();
//初始化spring容器,会自动创建带@Component注解的构造方法
ApplicationContext context=new AnnotationConfigApplicationContext(ApplicationSpring.class);
//从容器中获取MessagePrint对象
MessagePrint print=context.getBean(MessagePrint.class);
/**
* 可以使用@Autowired关联对象之间的关系
*/
//从容器中获取MessageService对象
//MessageServices services=context.getBean(MessageServices.class);
// print.setService(services);
print.printMessage();
}
}