ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

使用注解开发

2022-06-13 18:31:58  阅读:113  来源: 互联网

标签:name Component 开发 使用 xy 注解 public String


8、使用注解开发

在spring4之后,使用注解开发,必须要保证aop包的导入

使用注解需要导入contex的约束

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

</beans>

8.1 bean

需要在配置中加入< context:component-scan>标签。有了< context:component-scan>,另一个< context:annotation-config/>标签可以移除掉,因为已经被包含进去了。

<!--指定要扫描的包,这个包下面的注解才会生效
	别只扫一个com.xy.pojo包
	这里也可以用空格扫描多个包
--> 
<context:component-scan base-package="com.xy"/> 
<context:annotation-config/>

@Component注解

//@Component 注解
//等价于<bean id="user" classs"com.xy.pojo.User"/> 
@Component
public class User {  
     public String name ="xy";
}

8.2 属性注入 @value

@Component
public class User { 
    //相当于<property name="name" value="xy"/> 
    @value("xy") 
    public String name; 
    
    //也可以放在set方法上面
    //@value("xy")
    public void setName(String name) { 
        this.name = name; 
    }
}

8.3 衍生的注解

@Component有几个和它具有相同功能的衍生注解,会按照web开发中,mvc架构中分层。

  • dao (@Repository)
  • service(@Service)
  • controller(@Controller)

这四个注解的功能是一样的,都是代表将某个类注册到容器中


8.4 自动装配注解

@Autowired(与@Qualifier搭配使用):默认是byType方式,如果匹配不上,就会byName

@Nullable:字段标记了这个注解,说明该字段可以为空

@Resource:默认是byName方式,如果匹配不上,就会byType


8.5 作用域@scope

//原型模式prototype,单例模式singleton
//scope("prototype")相当于<bean scope="prototype"></bean>
@Component 
@scope("prototype")
public class User { 
    
    //相当于<property name="name" value="xy"/> 
    @value("xy") 
    public String name; 
    
    //也可以放在set方法上面
    @value("xy")
    public void setName(String name) { 
        this.name = name; 
    }
}

关于作用域的知识,回顾 [Bean作用域](##6.4 Bean作用域)


8.6 小结

xml与注解:

  • xml更加万能,维护简单,适用于任何场合
  • 注解,不是自己的类使用不了,维护复杂

最佳实践:

  • xml用来管理bean
  • 注解只用来完成属性的注入
  • 要开启注解支持

标签:name,Component,开发,使用,xy,注解,public,String
来源: https://www.cnblogs.com/xypersonal/p/16371878.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有