Spring注解@Componen、@Repository@Service、@Controller区别
spring注解@Component、@Service等自动生成bean的命名规则

spring注解@Component、@Service等⾃动⽣成bean的命名规则参考链接:信息来源今天碰到⼀个问题,写了⼀个@Service的bean,类名⼤致为:CUserxml配置:<context:component-scan base-package="com.xxx.xx.x"/>结果启动报错:No bean named 'cUser' is defined,即找不到名为cUser的beanbean的名字不是我预期的"cUser",临时将bean的名字硬性指定成了cUser来解决的,即:@Service("cUser")在⽹上找了半天,看到有位兄弟说得很有道理,引⽤⼀下(以下内容引⽤⾃篇⾸链接):但还是觉得⽐较奇怪,之前⼀直以为Spring对注解形式的bean的名字的默认处理就是将⾸字母⼩写,再拼接后⾯的字符,但今天看来不是这样的。
回来翻了⼀下原码,原来还有另外的⼀个特殊处理:当类的名字是以两个或以上的⼤写字母开头的话,bean的名字会与类名保持⼀致/** * Derive a default bean name from the given bean definition.* <p>The default implementation simply builds a decapitalized version* of the short class name: e.g. "mypackage.MyJdbcDao" -> "myJdbcDao".* <p>Note that inner classes will thus have names of the form* "outerClassName.InnerClassName", which because of the period in the* name may be an issue if you are autowiring by name.* @param definition the bean definition to build a bean name for* @return the default bean name (never {@code null})*/protected String buildDefaultBeanName(BeanDefinition definition) {String shortClassName = ClassUtils.getShortName(definition.getBeanClassName());return Introspector.decapitalize(shortClassName);}/** * Utility method to take a string and convert it to normal Java variable* name capitalization. This normally means converting the first* character from upper case to lower case, but in the (unusual) special* case when there is more than one character and both the first and* second characters are upper case, we leave it alone.* <p>* Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays* as "URL".** @param name The string to be decapitalized.* @return The decapitalized version of the string.*/public static String decapitalize(String name) {if (name == null || name.length() == 0) {return name;} // 如果发现类的前两个字符都是⼤写,则直接返回类名if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&Character.isUpperCase(name.charAt(0))){return name;} // 将类名的第⼀个字母转成⼩写,然后返回 char chars[] = name.toCharArray();chars[0] = Character.toLowerCase(chars[0]); return new String(chars);}。
Spring的四个基本注解ann...

Spring的四个基本注解ann...SpringMVC的四个基本注解annotation(控制层,业务层,持久层) -- @Component、@Repository @Service、@Controller SpringMVC中四个基本注解:@Component、@Repository @Service、@Controller看字面含义,很容易却别出其中三个:@Controller控制层,就是我们的action层@Service 业务逻辑层,就是我们的service或者manager 层@Repository持久层,就是我们常说的DAO层而@Component (字面意思就是组件),它在你确定不了事哪一个层的时候使用。
其实,这四个注解的效果都是一样的,Spring都会把它们当做需要注入的Bean加载在上下文中;但是在项目中,却建议你严格按照除Componen的其余三个注解的含义使用在项目中。
这对分层结构的web架构很有好处!!这里讲的是SpringMVC中这四个注解的作用,其实Srping中这四个注解的作用和SpringMVC一样.示例:1. 控制层@Controller // 注释为controller@RequestMapping("/login")public class LoginAction {@Autowired@Qualifier("userService") //注释指定注入 Beanprivate IUserService userService;。
其他略。
}2. 业务逻辑层@Service("userService")public class UserServiceImpl implements IUserService {@Autowired@Qualifier("userDao")private IUserDao userDao;。
聊聊注解@controller@service@component@repository的区别

聊聊注解@controller@service@component@repository的区别⽬录注解@controller@service@component@repository的区别命名不⼀样主要是为了区分类的作⽤和所属层级:Spring中的主要注解1.组件类注解@Component、@Repository、@Service、@Controller【创建注解】1.@Component标注为⼀个普通的springBean类2.@Repository标注为⼀个DAO层的组件类3.@Service标注为Service层(业务逻辑层)的组件类4.@Controller标注⼀个控制器组件类2.装配bean时常⽤注解@Autowired、@Resource【获取注解】2.1@Autowired【***常⽤】2.2@Resource(不属于spring的注解,是javax.annotation注解)2.3@Qualifier(不能单独使⽤)2.4@Autowired和@Qualifier的混合使⽤注解@controller@service@component@repository的区别查了⼀些⽹上的其他博客,发现⼏个注解本质上没有什么区别,⾄少在spring2.5版本⾥,这⼏个注解本质是⼀样的(当然,新的版本有什么变化⽬前还没细查)命名不⼀样主要是为了区分类的作⽤和所属层级:@Repository:持久层,⽤于标注数据访问组件,即DAO组件。
@Service:业务层,⽤于标注业务逻辑层主键。
@Controller:控制层,⽤于标注控制层组件。
@Component:当你不确定是属于哪⼀层的时候使⽤。
之所以区分开⼏种类型,⼀是spring想在以后的版本中为它们添加特殊技能,⼆是这种分层的做法使web架构更清晰,易读性与维护性更好。
/*** Indicates that an annotated class is a "Service", originally defined by Domain-Driven* Design (Evans, 2003) as "an operation offered as an interface that stands alone in the* model, with no encapsulated state."** <p>May also indicate that a class is a "Business Service Facade" (in the Core J2EE* patterns sense), or something similar. This annotation is a general-purpose stereotype* and individual teams may narrow their semantics and use as appropriate.** <p>This annotation serves as a specialization of {@link Component @Component},* allowing for implementation classes to be autodetected through classpath scanning.** @author Juergen Hoeller* @since 2.5* @see Component* @see Repository*/@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic @interface Service {/*** The value may indicate a suggestion for a logical component name,* to be turned into a Spring bean in case of an autodetected component.* @return the suggested component name, if any*/String value() default "";}从@service的源码看,service仍然是使⽤了@Component注解(@Controller与@Repository与service⼀样,这⾥就不贴源码了)。
Spring注解@component、@service、@Autowired等作用与区别

Spring注解@component、@service、@Autowired等作⽤与区别1、@Service⽤于标注业务层组件2、@Controller⽤于标注控制层组件(如struts中的action)3、@Repository⽤于标注数据访问组件,即DAO组件.4、@Component泛指组件,当组件不好归类的时候,我们可以使⽤这个注解进⾏标注。
5、@Autowired与@Resource的区别: @Autowired由Spring提供,只按照byType注⼊,默认情况下必须要求依赖对象存在,如果要允许null值,可以设置它的required属性为false。
如果想使⽤名称装配可以结合@Qualifier注解进⾏使⽤。
public class UserService {@Autowired@Qualifier(name="userDao1")private UserDao userDao;} @Resource由J2EE提供,默认按照byName⾃动注⼊,Spring将@Resource注解的name属性解析为bean的名字,type属性则解析为bean的类型。
所以如果使⽤name属性,则使⽤byName的⾃动注⼊策略,⽽使⽤type属性则使⽤byType⾃动注⼊策略。
①如果同时指定了name和type,则从Spring上下⽂中找到唯⼀匹配的bean进⾏装配,找不到则抛出异常。
②如果指定了name,则从上下⽂中查找名称(id)匹配的bean进⾏装配,找不到则抛出异常。
③如果指定了type,则从上下⽂中找到类似匹配的唯⼀bean进⾏装配,找不到或是找到多个,都会抛出异常。
④如果既没有指定name,⼜没有指定type,则⾃动按照byName⽅式进⾏装配;如果没有匹配,则回退为⼀个原始类型进⾏匹配,如果匹配则⾃动装配。
总结:@Resource的作⽤相当于@Autowired,只不过@Autowired按byType⾃动注⼊。
Spring常用的一些注解说明

Spring常⽤的⼀些注解说明@Configuration从Spring3.0,@Configuration⽤于定义配置类,可替换xml配置⽂件,被注解的类内部包含有⼀个或多个被@Bean注解的⽅法。
这些⽅法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进⾏扫描,并⽤于构建bean定义。
@Bean@Bean注解⽤于告诉⽅法,产⽣⼀个Bean对象,然后这个Bean对象交给Spring管理。
产⽣这个Bean对象的⽅法Spring只会调⽤⼀次,随后这个Spring将会将这个Bean对象放在⾃⼰的IOC容器中。
SpringIOC 容器管理⼀个或者多个bean,这些bean都需要在@Configuration注解下进⾏创建,在⼀个⽅法上使⽤@Bean注解就表明这个⽅法需要交给Spring进⾏管理。
@Autowired、@Resource@Resource和@Autowired注解都是⽤来实现依赖注⼊的。
只是@AutoWried按by type⾃动注⼊,⽽@Resource默认按byName⾃动注⼊。
♣ @Autowired@Autowired具有强契约特征,其所标注的属性或参数必须是可装配的。
如果没有Bean可以装配到@Autowired所标注的属性或参数中,⾃动装配就会失败,抛出NoSuchBeanDefinitionException.@Autowired可以对类成员变量、⽅法及构造函数进⾏标注,让 spring 完成 bean ⾃动装配的⼯作。
@Autowired 默认是按照类去匹配,配合 @Qualifier 指定按照名称去装配 bean。
♣ @Resource@Resource是JDK提供的注解,有两个重要属性,分别是name和type。
@Resource依赖注⼊时查找bean的规则既不指定name属性,也不指定type属性,则⾃动按byName⽅式进⾏查找。
Spring源码——@Component,@Service是如何被解析?

Spring源码——@Component,@Service是如何被解析?引⾔在Spring中,Component、Service是在⼯作中经常被使⽤到的注解,为了加深对Spring运⾏机制的理解,今天我们⼀起来看⼀下Spring中对Component等注解的处理⽅式Component注解源码在Component注解的源码中(已去掉多余⽆关内容)/*** Indicates that an annotated class is a "component".* Such classes are considered as candidates for auto-detection* when using annotation-based configuration and classpath scanning.*当使⽤基于注释的配置和类路径扫描时,此类将被视为⾃动检测的候选。
** <p>Other class-level annotations may be considered as identifying* a component as well, typically a special kind of component:* e.g. the {@link Repository @Repository} annotation or AspectJ's* 其他类级别的注释也可以被视为标识⼀个组件,通常是⼀种特殊的组件,,如Repository AspectJ注解* {@link ng.annotation.Aspect @Aspect} annotation.**/@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Indexedpublic @interface Component {/*** The value may indicate a suggestion for a logical component name,* to be turned into a Spring bean in case of an autodetected component.* @return the suggested component name, if any (or empty String otherwise)* 该值表明bean组件名称,以在⾃动检测到组件的情况下将其转换为Spring bean*/String value() default "";}上⾯第⼀段注释中其实已经告诉我们,Component 注解它是作为在基本注解⽅式配置Spring定义的时候,被其标注的类作为⾃动检测的候选对象通俗点讲就是,当使⽤Component-scan时,如果指定的包⾥⾯包含了被Component注解标识的类,其会被作为Spring bean对象,⾃动注册到Spring容器中。
springboot中@Mapper和@Repository的区别

public static void main(String[] args) {
SpringApplication.run(application.class,args); } }
网络错误503请刷新页面重试持续报错请尝试更换浏览器或网络环境
springboot中 @Mapper和 @Repository的区别
0--前 言
@Mapper和@Repository是常用的两个注解,两者都是用在dao上,两者功能差不多,容易混淆,有必要清楚其细微区别;
1--区 别
@Repository需要在Spring中配置扫描地址,然后生成Dao层的Bean才能被注入到Service层中:如下,在启动类中配置扫描地址:
@Mapper不需要配置扫描地址,通过xml里面的namespace里面的接口地址,生成了Bean后注入到Service层中。
也就是@Repository多了一个配置扫描地址的步骤;
SpringMVC常用注解@Controller,@Service,@repository。。。

SpringMVC常⽤注解@Controller,@Service,@repository。
SpringMVC常⽤注解@Controller,@Service,@repository,@Componentcontroller层使⽤@controller注解@Controller ⽤于标记在⼀个类上,使⽤它标记的类就是⼀个SpringMVC Controller 对象。
分发处理器将会扫描使⽤了该注解的类的⽅法。
通俗来说,被Controller标记的类就是⼀个控制器,这个类中的⽅法,就是相应的动作。
@RequestMapping是⼀个⽤来处理请求地址映射的注解,可⽤于类或⽅法上。
⽤于类上,表⽰类中的所有响应请求的⽅法都是以该地址作为⽗路径。
⽐如图⼀中,跳转到登录页⾯的路径就是localhost:8080/xxx-war/user/toLoginservice采⽤@service注解例:@Service("userService")注解是告诉,当Spring要创建UserServiceImpl的的实例时,bean的名字必须叫做"userService",这样当Action需要使⽤UserServiceImpl的的实例时,就可以由Spring创建好的"userService",然后注⼊给Action。
dao层使⽤@repository注解@Repository(value="userDao")注解是告诉Spring,让Spring创建⼀个名字叫“userDao”的UserDaoImpl实例。
当Service需要使⽤Spring创建的名字叫“userDao”的UserDaoImpl实例时,就可以使⽤@Resource(name = "userDao")注解告诉Spring,Spring把创建好的userDao注⼊给Service即可。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Spring 2.5 中除了提供@Component 注释外,还定义了几个拥有特殊语义的注释,它们分别是:@Repository、@Service 和@Controller。
在目前的Spring 版本中,这3 个注释和@Component 是等效的,但是从注释类的命名上,很容易看出这 3 个注释分别和持久层、业务层和控制层(Web 层)相对应。
虽然目前这 3 个注释和@Component 相比没有什么新意,但Spring 将在以后的版本中为它们添加特殊的功能。
所以,如果Web 应用程序采用了经典的三层分层结构的话,最好在持久层、业务层和控制层分别采用@Repository、@Service 和@Controller 对分层中的类进行注释,而用@Component 对那些比较中立的类进行注释。
在一个稍大的项目中,通常会有上百个组件,如果这些组件采用xml的bean定义来配置,显然会增加配置文件的体积,查找以及维护起来也不太方便。
Spring2.5为我们引入了组件自动扫描机制,他可以在类路径底下寻找标注了@Component,@Service,@Controller,@Repository注解的类,并把这些类纳入进spring容器中管理。
它的作用和在xml文件中使用bean节点配置组件时一样的。
要使用自动扫描机制,我们需要打开以下配置信息:Java代码1. <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="/schema/beans" xmlns:xsi="/2001/XMLSchema-instance"xmlns:context="/schema/context"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-2.5.xsd/schema/context/schema/context/spring-context-2.5.xsd"2. >3.4. <context:component-scan base-package=”com.eric.spring”>5. </beans>6. 其中base-package为需要扫描的包(含所有子包)@Service用于标注业务层组件,@Controller用于标注控制层组件(如struts中的action),@Repository用于标注数据访问组件,即DAO组件,而@Component 泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
7. @Service public class VentorServiceImpl implements iVentorService {8. } @Repository public class VentorDaoImpl implements iVentorDao {9. } getBean的默认名称是类名(头字母小写),如果想自定义,可以@Service(“aaaaa”)这样来指定,这种bean默认是单例的,如果想改变,可以使用@Service(“beanName”) @Scope(“prototype”)来改变。
可以使用以下方式指定初始化方法和销毁方法(方法名任意):@PostConstruct public void init() {10. }11. @PreDestroy public void destory() {12. }注入方式:把DAO实现类注入到service实现类中,把service的接口(注意不要是service的实现类)注入到action中,注入时不要new 这个注入的类,因为spring会自动注入,如果手动再new的话会出现错误,然后属性加上@Autowired后不需要getter()和setter()方法,Spring也会自动注入。
至于更具体的内容,等对注入的方式更•注册注解处理器•方式一:bean<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>•方式二: 命名空间<context:annotation-config /><context:annotationconfig /> 将隐式地向Spring 容器注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor 、 PersistenceAnnotationBeanPostProcessor 以及RequiredAnnotationBeanPostProcessor 这4 个BeanPostProcessor 。
•方式三: 命名空间<context:component-scan />如果要使注解工作,则必须配置component-scan ,实际上不需要再配置annotation-config。
base-package 属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理。
还允许定义过滤器将基包下的某些类纳入或排除。
• Spring 支持以下4 种类型的过滤方式:•注解 org.example.SomeAnnotation 将所有使用SomeAnnotation 注解的类过滤出来•类名指定 org.example.SomeClass 过滤指定的类•正则表达式 com.kedacom.spring.annotation.web..* 通过正则表达式过滤一些类• AspectJ 表达式 org.example..*Service+ 通过AspectJ 表达式过滤一些类•正则表达式的过滤方式举例:<context:component-scanbase-package="com.casheen.spring.annotation"><context:exclude-filtertype="regex"expression="com.casheen.spring.annotation.web..*"/></context:component-scan>•注解的过滤方式举例:<context:component-scan base-package="qin" ><context:include-filter type="annotation"expression="org.springframework.stereotype.Controller"/><context:include-filter type="annotation"expression="org.springframework.stereotype.Service"/><context:include-filter type="annotation"expression="org.springframework.stereotype.Repository"/></context:component-scan>注解:注解介绍• @Controller• @Service• @Autowired• @RequestMapping• @RequestParam• @ModelAttribute• @Cacheable• @CacheFlush• @Resource• @PostConstruct• @PreDestroy• @Repository• @Component (不推荐使用)• @Scope• @SessionAttributes• @InitBinder@Controller•例如@Controllerpublic class SoftCreateController extends SimpleBaseController {}•或者@Controller("softCreateController")•说明@Controller 负责注册一个bean 到spring 上下文中,bean 的ID 默认为类名称开头字母小写@Service•例如@Servicepublic class SoftCreateServiceImpl implements ISoftCreateService {}•或者@Service("softCreateServiceImpl")•说明@Service 负责注册一个bean 到spring 上下文中,bean 的ID 默认为类名称开头字母小写@Autowired•例如@Autowiredprivate ISoftPMService softPMService;•或者@Autowired(required=false)private ISoftPMService softPMService = new SoftPMServiceImpl();•说明@Autowired 根据bean 类型从spring 上线文中进行查找,注册类型必须唯一,否则报异常。
与@Resource 的区别在于,@Resource 允许通过bean 名称或bean 类型两种方式进行查找@Autowired(required=false) 表示,如果spring 上下文中没有找到该类型的bean 时,才会使用new SoftPMServiceImpl();@RequestMapping•类@Controller@RequestMapping("/bbtForum.do")public class BbtForumController {@RequestMapping(params = "method=listBoardTopic")public String listBoardTopic(int topicId,User user) {}}•方法@RequestMapping("/softpg/downSoftPg.do")@RequestMapping(value="/softpg/ajaxLoadSoftId.do",method = POST)@RequestMapping(value = "/osu/product/detail.do", params = { "modify=false" }, method =POST)•说明@RequestMapping 可以声明到类或方法上•参数绑定说明如果我们使用以下的 URL 请求:http://localhost/bbtForum.do?method=listBoardTopic&topicId=1&userId=10&userName=tom topicId URL 参数将绑定到 topicId 入参上,而 userId 和 userName URL 参数将绑定到 user 对象的 userId 和 userName 属性中。