- 组件扫描
@Component:表示这个类须在应用程序中被创建
@ComponentScan:自动发现应用程序中被创建的类 - 自动装配
@Autowired:自动满足bean之间的依赖 - 定义配置类
@Configuration:表示当前类是一个配置类 - 引入Spring单元测试模块
manvem:junit. spring-test
@RunWith(SpringJUnit4ClassRunner.class) - 加载配置类
@ContextConfiguration(classes=AppConfig.class)
pom.xml中导入外部依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zh</groupId>
<artifactId>spring02_xml</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
创建MessageService类
package hello;
import org.springframework.stereotype.Component;
/**
* 打印服务
*/
@Component //通知Spring容器,应用程序的对象也就是MessageService类的对象未来通过Spring容器自动创建出来,,不需要通过new来创建了。
public class MessageService {
public MessageService() {
super();
System.out.println("MessageSerice......");
}
/**
* 执行打印功能
* @return 返回打印的字符串
*/
public String getMessage() {
return "Hello World";
}
}
创建 MessagePrinter类
package hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 打印机
*/
@Component
public class MessagePrinter{
public MessagePrinter() {
super();
System.out.println("Messageprint......");
}
/**
* 建立和MessageService的关联关系
*/
private MessageService service;
/**
* 设置service的值
* @param service
*/
@Autowired//会自动调用setService
public void setService(MessageService service){
this.service = service;
}
public void printMessage(){
System.out.println(this.service.getMessage());
}
}
创建ApplicationSpring主类
package hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan //扫描所有有Component注解的类,自动创建到Spring容器中
public class ApplicationSpring {
public static void main(String[] args) {
System.out.println("applicationSpring");
// //创建打印机对象
// MessagePrinter printer = new MessagePrinter();
// //创建消息服务对象
// MessageService service = new MessageService();
// //设置打印对象的service属性
// printer.setService(service);
// //打印消息
// printer.printMessage();
//初始化Spring容器
ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationSpring.class);
//从容器中获取MessagePrinter对象
MessagePrinter printer = context.getBean(MessagePrinter.class);
//从容器中获取MessageService对象
// MessageService service = context.getBean(MessageService.class);
System.out.println(printer);
// System.out.println(service);
//设置打印对象的service属性
// printer.setService(service);
//打印消息
printer.printMessage();
}
}