Spring注解与P/C命名空间超详细解析

   2023-02-09 学习力0
核心提示:目录注解实现自动装配@Autowire注解@Qualifier注解@Resource注解@Component@Scope@ComponentScan@Bean@Configuration@ValueP命名空间注入C命名空间注入Spring开发包名解释Java方式配置注解实现自动装配@Autowire注解@Autowire注解,自动装配通过类型,名字如

注解实现自动装配

@Autowire注解

@Autowire注解,自动装配通过类型,名字如果Autowire不能唯一自动装配上属性,

则需要通过@Qualifier(value=“xxx”)

配置:

导入约束

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

开启注解支持

<context:annotation-config/>

实现:

Dog/Cat类和方法的实现还是不变

People类

  • 实现@Autowire注解、可以在属性上使用、也可以在set方式使用
  • 编写@Autowire注解后,set方法可以省略不写
public class People {
    @Autowired
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;
}

beans.xml

    <bean id="cat" class="com.wei.pojo.Cat"/>
    <bean id="dog" class="com.wei.pojo.Dog"/>
    <bean id="people" class="com.wei.pojo.People"/>

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

可以在带参构造中使用@Nullable

    public People(@Nullable String name) {
        this.name = name;
    }

@Qualifier注解

指定一个唯一的bean对象注入

People类

public class People {
    @Autowired
    @Qualifier(value = "cat111")
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog222")
    private Dog dog;
    private String name;
}

beans.xml

    <bean id="cat" class="com.wei.pojo.Cat"/>
    <bean id="cat111" class="com.wei.pojo.Cat"/>
    <bean id="dog" class="com.wei.pojo.Dog"/>
    <bean id="dog222" class="com.wei.pojo.Dog"/>
    <bean id="people" class="com.wei.pojo.People"/>

@Resource注解

默认按照名字装配Bean,即会按照name属性的值来找到具有相同id的Bean Definition 并注入

People类

public class People {
    @Resource(name = "cat2")
    private Cat cat;
    @Resource
    private Dog dog;
    private String name;
}

beans.xml

<bean id="cat1" class="com.wei.pojo.Cat"/>
<bean id="cat2" class="com.wei.pojo.Cat"/>
<bean id="dog" class="com.wei.pojo.Dog"/>
<bean id="people" class="com.wei.pojo.People"/>

总结:

  • @Autowire 通过byType方式实现,而且必须要求对象存在,不能为null
  • @Resource 默认通过byname的方式实现,如果找不到名字,则通过byType实现,都不行则报错

@Component

放在类上,说明这个类被Spring管理了,等同于bean配置

Java类

此处使用注解@Component @Value 则 beans.xml则无需书写bean

//等价于<bean id="user" class="com.wei.pojo.User       Component:组件
@Component
public class User {
    @Value("wei_shuo")  //相当于 <property name="name" value="wei_shuo"/>
    public String name;
}

@Component的衍生注解,在web开发中,按照MVC三层架构分层

四个注解功能、作用相同,都是代表将某个类注册到Spring中、装配Bean

  • pojo —> @Component
  • dao —> @Resource
  • service —> @Service
  • controller —> @Controller

@Scope

作用域注解,限定Spring Bean的作用范围,在Spring配置文件定义Bean时,通过声明scope配置项,可以灵活定义Bean的作用范围

@ComponentScan

@ComponentScan(“com.wei.pojo”) 扫描包

@Bean

  • 注册一个bean,就相当于bean标签
  • 方法的名字,相当于bean标签的id属性
  • 方法的返回值,相当于bean标签的class属性
    @Bean
    public User getUser(){
        return new User();      //就是返回要注入到bean的对象
    }

@Configuration

@Configuration注解会被Spring容器托管,因为它本身就是一个@Component

@Configuration 代表这是一个配置类,相当于beans.xml

@Configuration
@ComponentScan("com.wei.pojo")      
@Import(WeiConfig2.class)           
public class WeiConfig {
    @Bean
    public User getUser(){
        return new User();      
    }
}

@Value

属性注入值

Java类

此处使用@Scope注解使用prototype多实例注解模式

//等价于<bean id="user" class="com.wei.pojo.User       Component:组件
@Component
@Scope("prototype")		//作用域注解
public class User {
    @Value("wei_shuo")  //相当于 <property name="name" value="wei_shuo"/>
    public String name;
}

P命名空间注入

p命名空间注入,对应Set注入方式

需要创建set/get方法

p命名空间注入,可以直接注入属性的值:property

User类

package com.wei.pojo;
public class User {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

userbeans.xml文件

<?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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	<!--上面添加 xmlns:p="http://www.springframework.org/schema/p" -->
    <!--p命名空间注入,可以直接注入属性的值:property-->
    <bean id="user" class="com.wei.pojo.User" p:name="秦疆" p:age="18"/>
</beans>

Test测试

        ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
//        指定类型User.class则不需要强制转换
        User user = context.getBean("user", User.class);
//        强制转换
//        User user = (User) context.getBean("user");
        System.out.println(user);

C命名空间注入

c命名空间注入,对应构造器注入

需要创建无参/带参构造方法

c命名空间注入,通过构造器 注入:construct-args

User类

此处增加无参/带参构造方法

public class User {
    private String name;
    private int age;
    public User() {
    }
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

userbeans.xml文件

<?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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	<!--上面添加  xmlns:c="http://www.springframework.org/schema/c" -->
    <!--c命名空间注入,通过构造器 注入:construct-args-->
    <bean id="user2" class="com.wei.pojo.User" c:name="wei_shuo" c:age="18"/>
</beans>

Test测试

        ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
        User user = context.getBean("user2", User.class);
        System.out.println(user);

总结:

p命名空间注入/c命名空间注入 都需要导入xml约束,不能直接使用

xmlns:p=“http://www.springframework.org/schema/p”

xmlns:c=“http://www.springframework.org/schema/c”

Spring开发包名解释

dao包

数据库操作,crud 即增删改查,对于数据库的增删改查的操作都在这里

pojo包

简单java对象

service包

service 服务器层,也叫业务逻辑层,调用dao中的方法

Java方式配置

使用Java的方式配置Spring,也就是不写bean.xml配置,使用注解代替

实体列

//@Configurable放在类上,说明这个类被Spring管理了,等同于bean配置,注册到容器中
@Configurable
public class User {
    private String name;
    public String getName() {
        return name;
    }
    @Value("CSDN")  //属性注入值
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

配置文件

  • @Configuration注解会被Spring容器托管,因为它本身就是一个@Component
  • @Configuration 代表这是一个配置类,相当于beans.xml
  • @Import注解,功能就是和Spring XML里面的一样. @Import注解是用来导入配置类或者一些需要前置加载的类.通俗的将就是将类放入到IOC容器中
  • @Bean注解,注册一个bean,就相当于bean标签,方法的名字,相当于bean标签的id属性,方法的返回值,相当于bean标签的class属性
//@Configuration注解会被Spring容器托管,因为它本身就是一个@Component
//@Configuration 代表这是一个配置类,相当于beans.xml
@Configuration
@ComponentScan("com.wei.pojo")      //扫描包
@Import(WeiConfig2.class)           //@Import注解,功能就是和Spring XML里面的一样. @Import注解是用来导入配置类或者一些需要前置加载的类.通俗的将就是将类放入到IOC容器中
public class WeiConfig {
    //注册一个bean,就相当于bean标签
    //方法的名字,相当于bean标签的id属性
    //方法的返回值,相当于bean标签的class属性
    @Bean
    public User getUser(){
        return new User();      //就是返回要注入到bean的对象
    }
}

测试类

public class MyTest {
    //如果完全使用了配置类方式去做,只能通过AnnotationConfig 上下文来获取容器,通过配置类的class对象加载
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(WeiConfig.class);
        User getUser = (User) context.getBean("getUser");   //此处取方法名
        System.out.println(getUser.getName());
    }
}
原文地址:https://weishuo.blog.csdn.net/article/details/127456652
 
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • Springboot + mybatis + React+redux+React-rou
    前言:            后台搭建完以后开始搭建前端,使用create-react-app搭建项目非常方便。           前端主要是如何向后台请求数据,以及如何使用redux管理state,路由的配置.           前端github地址:  https://github.com
    02-09
  • 这个Spring Security登录插件牛啊,验证码、小程序、OAuth2都能快速接入
    这个Spring Security登录插件牛啊,验证码、小
    上次我们把验证码登录、小程序登录优雅地集成到了Spring Security,很多同学大呼过瘾,相比较一些传统玩法高级了很多。胖哥就赶紧抓住机会举一反三,把几个非标准的OAuth2也接入了进来,主要是微信、企业微信,做到应接尽接。只需要通过下面几行简单的代码就
    02-09 java
  • 微信小程序获取openId  SpringBoot
    微信小程序获取openId SpringBoot
    官方文档wx.login:【穿梭门】https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.htmlauth.code2Session【穿梭门】https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html案例小
    02-09
  • 微信小程序 springboot nginx 做图片存储 上传
    微信小程序前端-springboot后端-nginx图片存储前言本人小白一名,这是第一次学习微信小程序,特此做个记录。首先准备nginx做图片存储选择一个地址存放图片#我的地址[root@VM_0_16_centos images]# pwd/home/photos/images[root@VM_0_16_centos images]#然后配
    02-09
  • Ruby中文乱码问题 springmvc中文乱码
    中文乱码问题解决方法为只要在文件开头加入 # -*- coding: UTF-8 -*-(EMAC写法) 或者 #coding=utf-8 就行了。源代码文件中,若包含中文编码,则需要注意两点:1. 必须在首行添加 # -*- coding: UTF-8 -*-,告诉解释器使用utf-8来解析源码。2. 必须设置编
    02-09
  • SpringBoot + nodeJS + zookeeper 搭建微服务示
    总体来说该项目由服务注册 + 服务发现 + 服务代理 + 服务调用四部分组成。使用java客户的开发服务注册组件,它是整个微服务架构中的服务注册表,使用Node.js客户端开发服务发现组件,它用于在服务注册表中根据具体的服务名称获取对应的服务配置。  由项目1
    02-09
  • SpringBoot使用过滤器、拦截器和监听器的案例代
    目录SpringBoot使用过滤器、拦截器和监听器一、SpringBoot使用过滤器Spring boot过滤器的使用(两种方式)方式一:方式二:二、SpringBoot使用拦截器三、过滤器和拦截器的执行顺序四、SpringBoot使用监听器1、统计网站最多在线人数监听器的例子2、springboot
  • 一个C#开发者学习SpringCloud搭建微服务的心路历程
    一个C#开发者学习SpringCloud搭建微服务的心路
    前言Spring Cloud很火,很多文章都有介绍如何使用,但对于我这种初学者,我需要从创建项目开始学起,所以这些文章对于我的启蒙,帮助不大,所以只好自己写一篇文章,用于备忘。SpringCloud是封装了Netflix公司开发的Eureka模块来实现服务注册和发现。下图为Sp
    02-09
  • 微信小程序 部署(后台是springboot项目  前后台分离)
    微信小程序 部署(后台是springboot项目 前后
     微信小程序的部署需要https 和证书:   https 需要反向代理:   这里用 nginx,无论linux,windows 系统都可以安装:1.安装nginx ,这步自己去做;   linux 安装nginx 可以使用宝塔,或自己下载安装;2.配置nginx,把证书放在nginx安装目录conf 文件
    02-09
  • spring boot:redis+lua实现生产环境中可用的秒杀功能(spring boot 2.2.0)
    spring boot:redis+lua实现生产环境中可用的秒
    一,秒杀需要具备的功能:        秒杀通常是电商中用到的吸引流量的促销活动方式        搭建秒杀系统,需要具备以下几点:        1,限制每个用户购买的商品数量,(秒杀价格为吸引流量一般会订的很低,不能让一个用户全部抢购到手)        2,
    02-08
点击排行