Java 配置spring两种方式,XML与注解(通过@Configuration实现bean注入)

本文探讨了Spring框架中ApplicationContext的两种主要实现方式:注解配置和XML配置。注解配置通过在Java类上使用注解来定义bean,而XML配置则需要在XML文件中声明bean。示例展示了如何在JAVA配置类中创建ConfigurationUser和ConfigurationAddress bean,以及XML配置文件中如何指定扫描包和定义bean。这两种方式为Spring应用提供了灵活的初始化和管理组件的方式。

ApplicationContext 的实现类,点击左上角小图标可以查看,我们用到的主要是如下红框“注解实现”和“XML实现”两种方式

在这里插入图片描述

XML配置需要写xml文件

注解配置把相应配置写java文件里

在这里插入图片描述

JAVA配置类

package com.chenxb.config;

import com.chenxb.pojo.ConfigurationAddress;
import com.chenxb.pojo.ConfigurationUser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean
    public ConfigurationUser getConfigurationUser() {
        return new ConfigurationUser();
    }
    @Bean
    public ConfigurationAddress getConfigurationAddress() {
        return new ConfigurationAddress();
    }
//    @Bean
//    public ConfigurationAddress getConfigurationAddress() {
//        return new ConfigurationAddress();
//    }

}

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"
       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:component-scan base-package="com.chenxb.model"></context:component-scan>
<!--    <context:annotation-config/>-->
    <bean id="ComponentAddress" class="com.chenxb.model.ComponentAddress"  scope="singleton" />
<!--    <bean id="Address" class="com.chenxb.pojo.Address"/>-->
</beans>
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值