Spring-注解实现IOC

时间:2021-04-01 15:33:10

一、定义

注解:是一种标记式的配置方式,与XML配置文件不同,注解提供了更大的便捷性,易于维护修改,但是耦合度高。

本质:是一个继承了 Annotation 接口的接口,注解本身并没有什么作用,通过特殊方法解析才使得它起到它的作用。

二、注解实现IOC入门案例

导入包:

Spring-注解实现IOC

代码实现:

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan base-package="cn.zwj"></context:component-scan>
</beans>

XML配置文件

public interface TestService {
void save();
}

Service

 import org.springframework.stereotype.Service;
import cn.zwj.service.TestService; @Service
public class TestServiceImpl implements TestService {
@Override
public void save() {
System.out.println("保存用户--TestServiceImpl1");
} }

Service.impl

 import org.springframework.stereotype.Service;
import cn.zwj.service.TestService; @Service
public class TestServiceImpl2 implements TestService {
@Override
public void save() {
System.out.println("保存用户--TestServiceImpl2");
}
}

service.impl

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import cn.zwj.service.TestService; @Component
public class TestClient {
//1.声明一个父接口的引用
private TestService testService; //2.使用set方法注入对象,我们将通过方法注入对象的方式称之为依赖注入
@Autowired
public void setTestService(TestService testService) {
this.testService = testService;
} public void tryTest() {
testService.save();
}
}

client

 import org.springframework.context.support.ClassPathXmlApplicationContext;

 import cn.zwj.client.TestClient;

 public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:test.xml");
TestClient bean = context.getBean("testClient", TestClient.class);
bean.tryTest();
context.close();
}
}

test

从上面可以看出,注解减少了XML配置文件的编写,在各个类或类方法前添加了标记,使得代码看起来更加精简