学习笔记:2_Spring_AOP之基于注解方式配置Bean_2

Spring提供3个@Component注解衍生注解(功能一样)取代<bean class="">
@Component:基本注解,标识了一个受Spring管理的Bean组件
@Controller:标识表现层(Action层)Bean组件
@Service:标识服务层(业务层)Bean组件
@Repository:标识持久层(Dao层)Bean组件
目前4种注解意思是一样,并没有什么区别,区别只是名字不同。

@Autowired:表示自动装配,默认按类型匹配的方式,在容器查找匹配的Bean,

当有且仅有一个匹配的Bean时,Spring将其注入@Autowired标注的变量中。


1)        创建带有@Controller注解的表现层

package com.spring.scan;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

//@Controller:标识表现层(Action层)Bean组件
@Controller
public class TestAction {
//@Autowired:表示自动装配,默认按类型匹配的方式,在容器查找匹配的Bean,
//当有且仅有一个匹配的Bean时,Spring将其注入@Autowired标注的变量中。
@Autowired  //自动装配吵着IOC中有没有TestService类型的Bean
private TestService service;
public void execute(){
System.out.println("带有@Controller注解的表现层execute方法");
service.add();
}
}


2)        创建带有@Service注解的服务层

package com.spring.scan;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

//@Service:标识服务层(业务层)Bean组件
@Service
public class TestService {
//@Autowired:表示自动装配,默认按类型匹配的方式,在容器查找匹配的Bean,
//当有且仅有一个匹配的Bean时,Spring将其注入@Autowired标注的变量中。
@Autowired  //自动装配吵着IOC中有没有TestDao类型的Bean
private TestDao dao;
public void add(){
System.out.println("带有@Service注解的服务层add方法");
dao.insert();//通过注解方式装配后不需要new一个新对象了
}
}


3)        创建带有@Repository注解的持久层

package com.spring.scan;

import org.springframework.stereotype.Repository;

//@Repository:标识持久层(Dao层)Bean组件
@Repository
public class TestDao {
public void insert(){
System.out.println("带有@Repository注解的持久层insert方法");
}
}


4)        配置文件和main方法


扫描二维码关注公众号,回复: 1554857 查看本文章


5)        执行结果



猜你喜欢

转载自blog.csdn.net/wllno001/article/details/80616355