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

25 篇文章 1 订阅
16 篇文章 0 订阅

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值