首页 > 编程语言 >XML和javaConfig

XML和javaConfig

时间:2023-05-25 12:02:35浏览次数:36  
标签:XML xml name 配置文件 容器 javaConfig Student public

1. 为什么要使用 Spring Boot  1

1. 因为Spring, SpringMVC 需要使用的大量的配置文件 (xml文件)还需要配置各种对象,把使用的对象放入到spring容器中才能使用对象需要了解其他框架配置规则。

2. SpringBoot 就相当于 不需要配置文件的Spring+SpringMVC。 常用的框架和第三方库都已经配置好了。拿来就可以使用了。

3. SpringBoot开发效率高,使用方便多了

2.什么是JavaConfig  2

Spring 使用 Xml 作为容器配置文件, 在 3.0 以后加入了 JavaConfig. 使用 java 类做配

置文件使用。

2.1 什么是 JavaConfig  2

JavaConfig: 使用java类作为xml配置文件的替代, 是配置spring容器的纯java的方式。 在这个java类这可以创建java对象,把对象放入spring容器中(注入到容器), JavaConfig 是 Spring 提供的使用 java 类配置容器。 配置 Spring IOC 容器的纯 Java 方法。

2.1.1 优点:   2

1.可以使用面像对象的方式, 一个配置类可以继承配置类,可以重写方法

2.避免繁琐的 xml 配置

2.2 使用两个注解:  2

1)@Configuration : 放在一个类的上面,表示这个类是作为配置文件使用的。

2)@Bean:声明对象,把对象注入到容器中。

3. 使用配置文件xml方式配置容器 3

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.bjpowernode</groupId>
    <artifactId>course1</artifactId>
    <version>1.0.0</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.1</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <!-- 编译插件 -->
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <!-- 插件的版本 -->
                <version>3.5.1</version>
                <!-- 编译级别 -->
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <!-- 编码格式 -->
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

beans.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--使用xml文件配置容器  3
    声明bean对象-->
    <bean id="myStudent" class="com.bjpowernode.vo.Student">
        <property name="name" value="李思" />
        <property name="age" value="20" />
        <property name="sex" value="女" />
    </bean>

</beans>

Student

package com.bjpowernode.vo;

//student类  3
public class Student {

    private String name;
    private Integer age;
    private String sex;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}

测试 test01

/**
     * 使用xml作为容器配置文件  3
     */
    @Test
    public void test01(){
        String config="beans.xml";
        ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
        Student student = (Student) ctx.getBean("myStudent");
        System.out.println("容器中的对象:"+student);
    }

XML和javaConfig_spring

4. 使用javaConfig的方式配置容器   4

1)@Configuration : 放在一个类的上面,表示这个类是作为配置文件使用的。

2)@Bean:声明对象,把对象注入到容器中。

SpringConfig这个类就相当于beans.xml

说明:@Bean,不指定对象的名称,默认是方法名是 id

SpringConfig

package com.bjpowernode.config;

import com.bjpowernode.vo.Student;
import org.springframework.context.annotation.*;

/**
 * Configuration:表示当前类是作为配置文件使用的。 就是用来配置容器的   4
 *       位置:在类的上面
 *
 *  SpringConfig这个类就相当于beans.xml
 */
@Configuration
public class SpringConfig {

    /**
     * 创建方法,方法的返回值是对象。 在方法的上面加入@Bean
     * 方法的返回值对象就注入到容器中。
     *
     * @Bean: 把对象注入到spring容器中。 作用相当于
     *
     *     位置:方法的上面
     *
     *     说明:@Bean,不指定对象的名称,默认是方法名是 id
     *
     */
    @Bean
    public Student createStudent(){
        Student s1  = new Student();
        s1.setName("张三");
        s1.setAge(26);
        s1.setSex("男");
        return s1;
    }
}

测试test02

/**
     * 使用JavaConfig  4
     */
    @Test
    public void test02(){
        ApplicationContext ctx  = new AnnotationConfigApplicationContext(SpringConfig.class);
        Student student = (Student) ctx.getBean("createStudent");
        System.out.println("使用JavaConfig创建的bean对象:"+student);
    }

XML和javaConfig_配置文件_02

@Bean指定名称

/***
     * 指定对象在容器中的名称(指定的id属性)   4
     * @Bean的name属性,指定对象的名称(id)
     */
    @Bean(name = "lisiStudent")
    public Student makeStudent(){
        Student s2  = new Student();
        s2.setName("李四");
        s2.setAge(22);
        s2.setSex("男");
        return s2;
    }

test03

@Test
    public void test03(){
        ApplicationContext ctx  = new AnnotationConfigApplicationContext(SpringConfig.class);
        Student student = (Student) ctx.getBean("lisiStudent");
        System.out.println("使用JavaConfig创建的bean对象:"+student);
    }

XML和javaConfig_JavaConfig_03

5. @ImportResource   5

用法

@Configuration
@ImportResource(value ={ "classpath:applicationContext.xml","classpath:beans.xml"})
public class SpringConfig {
}

@ImportResource 是导入 xml 配置,等同于 xml 文件的 resources

applicationContext.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: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">

    <bean id="myCat" class="com.bjpowernode.vo.Cat">
        <property name="name" value="tom猫"/>
        <property name="age" value="2" />
        <property name="cardId" value="uw532423422"/>
    </bean>


</beans>

SpringConfig

package com.bjpowernode.config;

import com.bjpowernode.vo.Student;
import org.springframework.context.annotation.*;

/**
 * Configuration:表示当前类是作为配置文件使用的。 就是用来配置容器的   4
 *       位置:在类的上面
 *
 *  SpringConfig这个类就相当于beans.xml
 */
@Configuration
//@ImportResource是导入 xml 配置,等同于 xml 文件的 resources   5
@ImportResource(value = "classpath:applicationContext.xml")
public class SpringConfig {
}

test04

@Test
    public void test04(){
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        Cat cat  = (Cat) ctx.getBean("myCat");
        System.out.println("cat=="+cat);
    }

XML和javaConfig_配置文件_04

6. @PropertyResource   6

@PropertyResource 是读取 properties 属性配置文件 使用属性配置文件可以实现外部化配置 ,在程序代码之外提供数据。

6.1 步骤:  6

1. 在resources目录下,创建properties文件, 使用k=v的格式提供数据

2. 在PropertyResource 指定properties文件的位置

3. 使用@Value(value="${key}")

在 resources 目录下创建 config.properties

config.properties

tiger.name=东北老虎
tiger.age=3

Tiger

package com.bjpowernode.vo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

//演示@PropertyResource 是读取 properties 属性配置文件  6
@Component("tiger")
public class Tiger {

    @Value("${tiger.name}")
    private String name;
    @Value("${tiger.age}")
    private Integer age;

    @Override
    public String toString() {
        return "Tiger{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

SpringConfig

package com.bjpowernode.config;

import com.bjpowernode.vo.Student;
import org.springframework.context.annotation.*;

/**
 * Configuration:表示当前类是作为配置文件使用的。 就是用来配置容器的   4
 *       位置:在类的上面
 *
 *  SpringConfig这个类就相当于beans.xml
 */

@Configuration

//@ImportResource是导入 xml 配置,等同于 xml 文件的 resources   5
@ImportResource(value = "classpath:applicationContext.xml")

//@PropertyResource 是读取 properties 属性配置文件   6
@PropertySource(value = "classpath:config.properties")
@ComponentScan(basePackages = "com.bjpowernode.vo") //组件扫描器  6
public class SpringConfig {
}

test05

//@PropertyResource 是读取 properties 属性配置文件   6
    @Test
    public void test05(){
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
       Tiger tiger = (Tiger) ctx.getBean("tiger");
        System.out.println("tiger=="+tiger);
    }

XML和javaConfig_xml_05

7. 总结  6

SpringConfig中的这些注解,要是不写就要写在配置文件中

@Configuration
@ImportResource(value ={ "classpath:applicationContext.xml","classpath:beans.xml"})
@PropertySource(value = "classpath:config.properties")
@ComponentScan(basePackages = "com.bjpowernode.vo")
public class SpringConfig {
}

例如写在配置文件中

<context:property-placeholder location="classpath:config.properties" />
<context:component-scan base-package="com.bjpowernode.vo" />
<import resource="classpath:beans.xml" />

标签:XML,xml,name,配置文件,容器,javaConfig,Student,public
From: https://blog.51cto.com/u_15784725/6346410

相关文章

  • XML文件批量合并成Excel表格(Python)
    importosimportxml.etree.ElementTreeasETimportpandasaspdfolder_path="C:/xxx/Desktop/2022"#替换为你的文件夹路径#获取文件夹中的所有文件file_list=os.listdir(folder_path)#创建一个空的DataFrame来存储所有XML文件的数据all_data=pd.DataFra......
  • 【SQL用法】Mybatis框架中的xml文件中经常使用的sql语句
    本文目录一、insert语句二、select查询语句三、批量添加四、与时间比较相关的项目中经常会用到的sql语句有:一、insert语句<!--保存用户信息--><insertid="save">insertintomainsite_product_message<trimprefix="("suffix=")"suffixOverrides=","......
  • 【IntelliJ IDEA】idea中的插件之一:Free Mybatis plugin跳转插件的使用(方便在Dao接口
    本文目录一、安装二、使用最近在使用一个非常好用的跳转插件,用着很顺手,效率比之前提高了很多。之前使用MyBatis框架或者是在IDEA中,发现Mapper接口和XML文件之间跳转十分的麻烦,我之前经常的操作是在Mapper接口中将接口名称复制一下,然后去查找对应的XML文件,打开后CRTL+F查找对应的xml......
  • xml基础
    一.XML基础1.XML简介XML是指可扩展标记语言(ExtensibleMarkupLanguage),它是一种标记语言,很类似HTML。它被设计的初衷是为了替换html,但没有替换成功,所以就退居幕后,常用作配置文件。XML标签没有被预定义,需要用户自行定义标签。XML技术是W3C组织(WorldWideWebConsortium万......
  • 爬取 万年历 xml 操作
    importdatetimeimportrequestsimportxml.etree.ElementTreeasETkw={'wd':'python教程'}url1='https://rili.ximizi.com/jinrijishi.php'url2='https://www.xingzuo5.net/calendar/2025/2025-12-22.html'headers={'User......
  • odoo关于 xml <template>标签 的继承修改方法
    写法同之前的视图继承比较相似,话不多说,直接上案例比如我需在在下列报表添加barcode或者其他字段 第一步先找到当前的视图位置,具体查找方法以后再讲。最后找到视图 这里面的id还有这个xml文件所在的包会在后面用到以上信息确认完毕之后,就可以直接写继承了自定义......
  • 让java目录能导出.xml配置文件
    在maven中配置<!--插件配置--><build><resources><resource><directory>src/main/java</directory><!--包含了src/main/java目录下的所有xml资源配置文件--><includes......
  • XML解析之DOM解析
    XML解析之DOM解析XML结构是一种树型结构,处理步骤都差不多,Java己经将它们封装成了现成的类库。目前流行的解析方法有三种,分别为DOM、SAX和DOM4j。本文将讲解DOM解析。DOM(DocumentObjectModel,文档对象模型)是W3C组织推荐的处理XML的一种方式。它是一种基于对象的API,......
  • 编写javaweb用到的基本依赖,mybatis-config.xml代码,SqlSessionFactoryUtils.java
    这篇文章仅仅作为记录,供以后复制粘贴使用pom.xml<dependencies><!--Servlet--><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</vers......
  • python解析XML
    xml简介XML全称ExtensibleMarkupLanguage,中文译为可扩展标记语言。XML之前有两个先行者:SGML和HTML,率先登场的是SGML,尽管它功能强大,但文档结构复杂,既不容易学也不易于使用,因此几个主要的浏览器厂商均拒绝支持SGML,这些因素限制了SGML在网上的传播性;1989年HTML登场,它继......