以xml和注解的方式,编写IOC和DI的案例,并进行测试(编程题)50‘
时间: 2023-07-15 15:12:41 浏览: 99
这里提供一个使用XML配置文件和注解方式实现IOC和DI的案例,并进行测试。
首先,我们需要定义一个接口和它的实现类:
```
public interface MessageService {
String getMessage();
}
public class MessageServiceImpl implements MessageService {
public String getMessage() {
return "Hello, World!";
}
}
```
然后,我们使用XML配置文件定义Bean:
```
<bean id="messageService" class="com.example.MessageServiceImpl"/>
```
接着,我们使用注解定义依赖注入:
```
@Component
public class MessagePrinter {
@Autowired
private MessageService messageService;
public void printMessage() {
System.out.println(messageService.getMessage());
}
}
```
最后,我们编写测试代码:
```
public class MessagePrinterTest {
private ApplicationContext context;
@Before
public void setUp() {
context = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void testPrintMessage() {
MessagePrinter printer = context.getBean(MessagePrinter.class);
printer.printMessage();
}
}
```
在测试代码中,我们使用ClassPathXmlApplicationContext来加载XML配置文件,并使用context.getBean方法获取MessagePrinter对象。由于MessagePrinter类使用了@Autowired注解,Spring会自动将MessageService对象注入到MessagePrinter中。
运行测试代码,可以看到输出了"Hello, World!"。
完整的示例代码如下:
MessageService.java:
```
public interface MessageService {
String getMessage();
}
```
MessageServiceImpl.java:
```
public class MessageServiceImpl implements MessageService {
public String getMessage() {
return "Hello, World!";
}
}
```
MessagePrinter.java:
```
@Component
public class MessagePrinter {
@Autowired
private MessageService messageService;
public void printMessage() {
System.out.println(messageService.getMessage());
}
}
```
applicationContext.xml:
```
<bean id="messageService" class="com.example.MessageServiceImpl"/>
<context:component-scan base-package="com.example"/>
```
MessagePrinterTest.java:
```
public class MessagePrinterTest {
private ApplicationContext context;
@Before
public void setUp() {
context = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void testPrintMessage() {
MessagePrinter printer = context.getBean(MessagePrinter.class);
printer.printMessage();
}
}
```
阅读全文