Spring从入门到入土(bean的一些子标签及注解的使用)

简介: 本文详细介绍了Spring框架中Bean的创建和使用,包括使用XML配置文件中的标签和注解来创建和管理Bean,以及如何通过构造器、Setter方法和属性注入来配置Bean。

类目录结构

public class Cpu {
    private Integer num;
    private String cpuName;
    private String factory;

    public Cpu() {
    }

    public Cpu(Integer num, String cpuName, String factory) {
        this.num = num;
        this.cpuName = cpuName;
        this.factory = factory;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    public void setCpuName(String cpuName) {
        this.cpuName = cpuName;
    }

    public void setFactory(String factory) {
        this.factory = factory;
    }

    @Override
    public String toString() {
        return "Cpu{" +
                "num=" + num +
                ", cpuName='" + cpuName + '\'' +
                ", factory='" + factory + '\'' +
                '}';
    }
}
public class Computer {
    private Integer num;
    private String computerName;
    private Cpu cpu;

    public Computer() {
    }

    public Computer(Integer num, String computerName, Cpu cpu) {
        this.num = num;
        this.computerName = computerName;
        this.cpu = cpu;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    public void setComputerName(String computerName) {
        this.computerName = computerName;
    }

    public void setCpu(Cpu cpu) {
        this.cpu = cpu;
    }

    @Override
    public String toString() {
        return "Computer{" +
                "num=" + num +
                ", computerName='" + computerName + '\'' +
                ", cpu=" + cpu +
                '}';
    }
}
public class SuperComputer {
    private String[] computerNames;
    private List<String> factorys;
    private Set<Cpu> cpus;
    private Map<Integer,String> users;
    private Properties userGirls;

    public void setComputerNames(String[] computerNames) {
        this.computerNames = computerNames;
    }

    public void setFactorys(List<String> factorys) {
        this.factorys = factorys;
    }

    public void setCpus(Set<Cpu> cpus) {
        this.cpus = cpus;
    }

    public void setUsers(Map<Integer, String> users) {
        this.users = users;
    }

    public void setUserGirls(Properties userGirls) {
        this.userGirls = userGirls;
    }

    @Override
    public String toString() {
        return "SuperComputer{" +
                "computerNames=" + Arrays.toString(computerNames) +
                ", factorys=" + factorys +
                ", cpus=" + cpus +
                ", users=" + users +
                ", userGirls=" + userGirls +
                '}';
    }
}
<?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 
       https://www.springframework.org/schema/context/spring-context.xsd">
</beans>

1. 使用无参构造创建对象

在xml文件中加入

<bean id="cpu" class="org.example.IOC.Cpu"></bean>
    @Test
    public void cpuTest(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring_bean.xml");

        Cpu bean1 = (Cpu) context.getBean("cpu");
        System.out.println(bean1);

    }

2. 使用有参构造创建对象

    <bean id="cpu" class="org.example.IOC.Cpu">
        <!-- 通过类型定位属性-->
        <constructor-arg type="java.lang.Integer" value="123"></constructor-arg>
        <!--通过下标定位属性-->
        <constructor-arg index="1" value="Inter"></constructor-arg>
        <!--通过属性名定位属性-->
        <constructor-arg name="factory" value="InterFactory"></constructor-arg>
    </bean>
    @Test
    public void cpuTest(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring_bean.xml");

        Cpu bean1 = (Cpu) context.getBean("cpu");
        System.out.println(bean1);

    }

3. 带有类类型属性的构造器创建对象

   @Test
    public void cpuTest(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring_bean.xml");

        Computer computer = (Computer) context.getBean("computer");
        System.out.println(computer);
    }
    <bean id="cpu" class="org.example.IOC.Cpu">
        <!-- 通过类型定位属性-->
        <constructor-arg type="java.lang.Integer" value="123"></constructor-arg>
        <!--通过下标定位属性-->
        <constructor-arg index="1" value="Inter"></constructor-arg>
        <!--通过属性名定位属性-->
        <constructor-arg name="factory" value="InterFactory"></constructor-arg>
    </bean>
    <!--构造器方法赋值-->
    <bean id="computer" class="org.example.IOC.Computer">
        <constructor-arg name="num" value="100"></constructor-arg>
        <constructor-arg name="computerName" value="外星人"></constructor-arg>
        <constructor-arg name="cpu" ref="cpu"></constructor-arg>
    </bean>

    <bean id="computer" class="org.example.IOC.Computer">
        <constructor-arg name="num" value="100"></constructor-arg>
        <constructor-arg name="computerName" value="外星人"></constructor-arg>
        <constructor-arg name="cpu">
            <bean class="org.example.IOC.Cpu">
                <constructor-arg type="java.lang.Integer" value="666"></constructor-arg>
                <constructor-arg index="1" value="Inter"></constructor-arg>
                <constructor-arg name="factory" value="InterFactory"></constructor-arg>
            </bean>
        </constructor-arg>
    </bean>

4. 使用Set方法传递参数

    @Test
    public void cpuTest(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring_bean.xml");

        Computer computer1 = (Computer) context.getBean("computer1");
        System.out.println(computer1);
    }
    <bean id="cpu" class="org.example.IOC.Cpu">
        <!-- 通过类型定位属性-->
        <constructor-arg type="java.lang.Integer" value="123"></constructor-arg>
        <!--通过下标定位属性-->
        <constructor-arg index="1" value="Inter"></constructor-arg>
        <!--通过属性名定位属性-->
        <constructor-arg name="factory" value="InterFactory"></constructor-arg>
    </bean>
    <!--Set方法传参数-->
    <bean id="computer1" class="org.example.IOC.Computer">
        <!--name: 指定set方法   value: 传入的值-->
        <property name="num" value="200"></property>
        <property name="computerName" value="苹果"></property>
        <!--ref: 引用spring容器中的对象-->
        <property name="cpu" ref="cpu"></property>
    </bean>

5. 集合, 数组的参数传递

    @Test
    public void cpuTest(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring_bean.xml");

        SuperComputer superComputer = (SuperComputer) context.getBean("superComputer");
        System.out.println(superComputer);
    }
   <bean id="superComputer" class="org.example.IOC.SuperComputer">
        <property name="computerNames">
            <array>
                <value>MacPro</value>
                <value>外星人</value>
            </array>
        </property>

        <property name="factorys">
            <list>
                <value>因特尔工厂</value>
                <value>苹果工厂</value>
            </list>
        </property>

        <property name="cpus">
            <set>
                <bean class="org.example.IOC.Cpu">
                    <constructor-arg name="num" value="111"></constructor-arg>
                    <constructor-arg name="cpuName" value="Inter"></constructor-arg>
                    <constructor-arg name="factory" value="因特尔工厂"></constructor-arg>
                </bean>
                <bean class="org.example.IOC.Cpu">
                    <constructor-arg name="num" value="222"></constructor-arg>
                    <constructor-arg name="cpuName" value="苹果"></constructor-arg>
                    <constructor-arg name="factory" value="苹果工厂"></constructor-arg>
                </bean>
            </set>
        </property>

        <property name="users">
            <map>
                <entry key="1" value="张三"></entry>
                <entry key="2" value="李四"></entry>
            </map>
        </property>

        <property name="userGirls">
            <props>
                <prop key="1">貂蝉</prop>
                <prop key="2">西施</prop>
            </props>
        </property>
    </bean>

6. 注解的使用

    <!--扫描整个包-->
    <context:component-scan base-package="org.example.IOC"></context:component-scan>

6.1 类注解的使用

    **@Component
    @Service        业务层
    @Controller     表现层
    @Repository     持久层**
//@Component(value = "cpu")
@Component     //默认id: 类名首字母小写

//@Service(value = "cpu")
//@Service

//@Controller(value = "cpu")
//@Controller

//@Repository(value = "cpu")
//@Repository

public class Cpu {
    private Integer num;
    private String cpuName;
    private String factory;

   //...此处省略(与上方对应类代码相同)
}
  @Test
    public void Test02(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring_bean.xml");

        //注解的使用
        Cpu bean = (Cpu) context.getBean("cpu");
        System.out.println(bean);
    }

6.1 @Value注解的使用

@Component     //默认id: 类名首字母小写
public class Cpu {
    @Value("666")
    private Integer num;
    @Value("因特尔")
    private String cpuName;
    @Value("InterFactory")
    private String factory;

    //....此处省略(与上面代码一样)
}

6.2 类类型属性注解的使用

@Autowired
@Qualifier(value = "cpu")

@Resource(name = "cpu")
@Component
public class Computer {
    private Integer num;
    private String computerName;
    @Autowired
    @Qualifier(value = "cpu")

    //@Resource(name = "cpu")
    private Cpu cpu;

   //...此处省略(与上方对应类代码相同)
}

6.3 单例多例注解的使用

@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)  //单例
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)  //多例
public class Computer {
    ......
}

6.4 @PostConstruct和@PreDestroy注解的使用

@Component
public class Computer {
    private Integer num;
    private String computerName;
    @Autowired
    @Qualifier(value = "cpu")
    private Cpu cpu;

    //...此处省略(与上方对应类代码相同)

//创建容器时调用
    @PostConstruct
    public void initMethod(){
        System.out.println("容器被创建!");
    }
//销毁容器时调用
    @PreDestroy
    public void destroyMethod(){
        System.out.println("容器被销毁!");
    }
}
   @Test
    public void Test02(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring_bean.xml");

        ((ClassPathXmlApplicationContext)context).close();
    }

单例模式下:

6.5 通过字节码获取对象

  @Test
    public void Test02(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring_bean.xml");

        //通过字节码拿到对象
        //缺点: 当配置了多个bean时, 因为字节码是相同的,因此会造成混淆(不知道给你返回哪一个bean)
        Cpu bean = context.getBean(Cpu.class);
        System.out.println(bean);
    }

相关文章
|
27天前
|
弹性计算 人工智能 架构师
阿里云携手Altair共拓云上工业仿真新机遇
2024年9月12日,「2024 Altair 技术大会杭州站」成功召开,阿里云弹性计算产品运营与生态负责人何川,与Altair中国技术总监赵阳在会上联合发布了最新的“云上CAE一体机”。
阿里云携手Altair共拓云上工业仿真新机遇
|
3天前
|
人工智能 Rust Java
10月更文挑战赛火热启动,坚持热爱坚持创作!
开发者社区10月更文挑战,寻找热爱技术内容创作的你,欢迎来创作!
363 14
|
19天前
|
存储 关系型数据库 分布式数据库
GraphRAG:基于PolarDB+通义千问+LangChain的知识图谱+大模型最佳实践
本文介绍了如何使用PolarDB、通义千问和LangChain搭建GraphRAG系统,结合知识图谱和向量检索提升问答质量。通过实例展示了单独使用向量检索和图检索的局限性,并通过图+向量联合搜索增强了问答准确性。PolarDB支持AGE图引擎和pgvector插件,实现图数据和向量数据的统一存储与检索,提升了RAG系统的性能和效果。
|
6天前
|
JSON 自然语言处理 数据管理
阿里云百炼产品月刊【2024年9月】
阿里云百炼产品月刊【2024年9月】,涵盖本月产品和功能发布、活动,应用实践等内容,帮助您快速了解阿里云百炼产品的最新动态。
阿里云百炼产品月刊【2024年9月】
|
21天前
|
人工智能 IDE 程序员
期盼已久!通义灵码 AI 程序员开启邀测,全流程开发仅用几分钟
在云栖大会上,阿里云云原生应用平台负责人丁宇宣布,「通义灵码」完成全面升级,并正式发布 AI 程序员。
|
23天前
|
机器学习/深度学习 算法 大数据
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
2024“华为杯”数学建模竞赛,对ABCDEF每个题进行详细的分析,涵盖风电场功率优化、WLAN网络吞吐量、磁性元件损耗建模、地理环境问题、高速公路应急车道启用和X射线脉冲星建模等多领域问题,解析了问题类型、专业和技能的需要。
2592 22
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
|
5天前
|
存储 人工智能 搜索推荐
数据治理,是时候打破刻板印象了
瓴羊智能数据建设与治理产品Datapin全面升级,可演进扩展的数据架构体系为企业数据治理预留发展空间,推出敏捷版用以解决企业数据量不大但需构建数据的场景问题,基于大模型打造的DataAgent更是为企业用好数据资产提供了便利。
181 2
|
3天前
|
编译器 C#
C#多态概述:通过继承实现的不同对象调用相同的方法,表现出不同的行为
C#多态概述:通过继承实现的不同对象调用相同的方法,表现出不同的行为
105 65
|
6天前
|
Linux 虚拟化 开发者
一键将CentOs的yum源更换为国内阿里yum源
一键将CentOs的yum源更换为国内阿里yum源
331 2
|
23天前
|
机器学习/深度学习 算法 数据可视化
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码
2024年中国研究生数学建模竞赛C题聚焦磁性元件磁芯损耗建模。题目背景介绍了电能变换技术的发展与应用,强调磁性元件在功率变换器中的重要性。磁芯损耗受多种因素影响,现有模型难以精确预测。题目要求通过数据分析建立高精度磁芯损耗模型。具体任务包括励磁波形分类、修正斯坦麦茨方程、分析影响因素、构建预测模型及优化设计条件。涉及数据预处理、特征提取、机器学习及优化算法等技术。适合电气、材料、计算机等多个专业学生参与。
1580 17
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码