随笔录 之 spring 自学杂记(二) -- IOC(二)

3.基于注解的配置

声明bean类或者组件有两种方式:

1、采用 XML 来描述一个 bean 连线

2、注解方式--Spring是能够自动扫描,检测和预定义的项目包并实例化bean

1、首先要在spring.xml中添加:

		<!-- 注解方式 -->
	<context:component-scan base-package="com.wm.spring.Annotation"/> 

当<context:annotation-config/>配置后,您就可以开始注释代码表明,Spring自动扫码base-package下的包,自动连线的值到属性,方法和构造函数。

但是要在spring.xml文件中引入context规范约束

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
			http://www.springframework.org/schema/mvc 
			http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 
			http://www.springframework.org/schema/context 
			http://www.springframework.org/schema/context/spring-context-4.0.xsd 
			http://www.springframework.org/schema/aop 
			http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
			http://www.springframework.org/schema/tx 
			http://www.springframework.org/schema/tx/spring-tx-4.0.xsd ">

2、在bean类或者组件中添加 注解


控制层:

@Controller
public class StudentController {

	@Autowired
	private StudentService service ;
	
	public void doTestAnnotation(){
		service.doTestAnnotation();
		System.out.println("StudentController ......");
	}
}
服务层:

@Service
public class StudentService {

	@Autowired
	private StudentDao dao ;
	
	public void doTestAnnotation(){
		dao.doTestAnnotation();
		System.out.println("StudentService .......");
	}
	
}
DAO层:
@Repository
public class StudentDao {
	public void doTestAnnotation(){
		System.out.println("StudentDao .......");
	}
}

测试:

	@Test
	public void TestAnnotation(){
		
		System.out.println("注解方式:");
		
		StudentController sc = (StudentController)ac.getBean("studentController");
		sc.doTestAnnotation();
		
	}

结果:

信息: Loading XML bean definitions from class path resource [spring.xml]
注解方式:
StudentDao .......
StudentService .......
StudentController ......


3、常用注解

  • @Component – 指示自动扫描组件。
  • @Repository – 表示在持久层DAO组件。
  • @Service – 表示在业务层服务组件。
  • @Controller – 表示在表示层控制器组件。
  • @Autowired -表示自动匹配(按照类名)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天涯共明月

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值