Spring成神之路第十七篇:@Configration 和@Bean 注解详解(bean 批量注册)

Spring系列第17篇:@Configration和@Bean注解 使用步骤:在类上使用注解通过容器来加注解修饰的类@Bean注解无论是哪家公司,都很重视基础,大厂更加重视技术的深度和广度,面试是一个双向选择的过程,不要抱着畏惧的心态去面试,不利于自己的发挥。同时看中的应该不止薪资,还要看你是不是真的喜欢这家公司,是不是能真的得到锻炼。针对以上面试技术点,我在这里也做一些分享,希望能更好的帮助到大家。《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!大家的负担。 阅读详情

Spring成神之路第十七篇:@Configration 和@Bean 注解详解(bean 批量注册)

上次去头条面试:

面试官:spring中,类上加不加@Configuration注解,有什么区别?

我:当某个类上有@Configuration注解的时候,可以在这个类中使用@Bean注解向spring容器中注册bean;如果不加@Configuration注解,不能通过@Bean注解注册bean。

面试官:你确定不用@Configuration注解,不能通过@Bean注解来注册bean?

我:看着面试官,犹豫了10秒钟,说:不加@Configuration通过@Bean注解也可以注册bean

面试官:你确定可以注册?

我:嗯。。。。嗯。。。。嗯,我确定可以注册

面试官:那加不加到底有什么区别呢?

我:好像没有什么区别啊

面试官:好像没区别。。。。先回去等通知吧!

结果可想而知,没戏了!

回去之后立即看spring的源码,终于搞清了这个问题,原来加不加@Configuration还是有相当大的区别的。

下面我们就来看看@Configuration注解到底是干什么的,加不加到底有什么区别,下次你们去面试的时候就可以给面试官吹吹了。

之前我们都是通过xml的方式定义bean,里面会写很多bean元素,然后spring启动的时候,就会读取bean xml配置文件,然后解析这些配置,然后会将这些bean注册到spring容器中,供使用者使用。

jdk1.5里面有了注解的功能,spring也没闲着,觉得注解挺好用的,就将注解加了进来,让我们通过注解的方式来定义bean,用起来能达到xml中定义bean一样的效果,并且更简洁一些,这里面需要用到的注解就有@Configuration注解和@Bean注解。

@Configuration注解

用法

@Configuration这个注解可以加在类上,让这个类的功能等同于一个bean xml配置文件,如下:

@Configuration
public class ConfigBean {

}

上面代码类似于下面的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-4.3.xsd">

</beans>

通过AnnotationConfigApplicationContext来加载@Configuration修饰的类,如下:

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConfigBean.class);

此时ConfigBean类中没有任何内容,相当于一个空的xml配置文件,此时我们要在ConfigBean类中注册bean,那么我们就要用到@Bean注解了。

总结一下

@Configuration使用步骤:

  1. 在类上使用@Configuration注解
  2. 通过AnnotationConfigApplicationContext容器来加@Configuration注解修饰的类

@Bean注解

用法

这个注解类似于bean xml配置文件中的bean元素,用来在spring容器中注册一个bean。

@Bean注解用在方法上,表示通过方法来定义一个bean,默认将方法名称作为bean名称,将方法返回值作为bean对象,注册到spring容器中。

如:

@Bean
public User user1() {
    return new User();
}

@Bean注解还有很多属性,我们来看一下其源码:

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) //@1
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {

    @AliasFor("name")
    String[] value() default {};

    @AliasFor("value")
    String[] name() default {};

    @Deprecated
    Autowire autowire() default Autowire.NO;

    boolean autowireCandidate() default true;

    String initMethod() default "";

    String destroyMethod() default AbstractBeanDefinition.INFER_METHOD;
}

@1:说明这个注解可以用在方法和注解类型上面。

每个参数含义:

  1. value和name是一样的,设置的时候,这2个参数只能选一个,原因是@AliasFor导致的

    @AliasFor这个注解不清楚的可以看这个文章:详解注解

  2. value:字符串数组,第一个值作为bean的名称,其他值作为bean的别名

  3. autowire:这个参数上面标注了@Deprecated,表示已经过期了,不建议使用了

  4. autowireCandidate:是否作为其他对象注入时候的候选bean,之前的文章中专门介绍过这个属性,不清楚的可以去看看:autowire-candidate详解

  5. initMethod:bean初始化的方法,这个和生命周期有关,以后详解

  6. destroyMethod:bean销毁的方法,也是和生命周期相关的,以后详解

案例

User类
package com.javacode2018.lesson001.demo20;

public class User {
}
Bean配置类:ConfigBean
package com.javacode2018.lesson001.demo20;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ConfigBean {

    //bean名称为方法默认值:user1
    @Bean
    public User user1() {
        return new User();
    }

    //bean名称通过value指定了:user2Bean
    @Bean("user2Bean")
    public User user2() {
        return new User();
    }

    //bean名称为:user3Bean,2个别名:[user3BeanAlias1,user3BeanAlias2]
    @Bean({"user3Bean", "user3BeanAlias1", "user3BeanAlias2"})
    public User user3() {
        return new User();
    }

}

上面通过@Bean注解定义了3个bean,比较简单

来个测试类
package com.javacode2018.lesson001.demo20;

import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.Arrays;

public class ConfigurationTest {
    @Test
    public void test1() {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConfigBean.class);//@1
        for (String beanName : context.getBeanDefinitionNames()) {
            //别名
            String[] aliases = context.getAliases(beanName);
            System.out.println(String.format("bean名称:%s,别名:%s,bean对象:%s",
                    beanName,
                    Arrays.asList(aliases),
                    context.getBean(beanName)));
        }
    }
}

@1:通过AnnotationConfigApplicationContext来加载配置类ConfigBean,会将配置类中所有的bean注册到spring容器中

for循环中输出了bean名称、别名、bean对象

运行test1方法输出
bean名称:org.springframework.context.annotation.internalConfigurationAnnotationProcessor,别名:[],bean对象:org.springframework.context.annotation.ConfigurationClassPostProcessor@3bd82cf5
bean名称:org.springframework.context.annotation.internalAutowiredAnnotationProcessor,别名:[],bean对象:org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor@544fa968
bean名称:org.springframework.context.annotation.internalCommonAnnotationProcessor,别名:[],bean对象:org.springframework.context.annotation.CommonAnnotationBeanPostProcessor@247bddad
bean名称:org.springframework.context.event.internalEventListenerProcessor,别名:[],bean对象:org.springframework.context.event.EventListenerMethodProcessor@d35dea7
bean名称:org.springframework.context.event.internalEventListenerFactory,别名:[],bean对象:org.springframework.context.event.DefaultEventListenerFactory@7770f470
bean名称:configBean,别名:[],bean对象:com.javacode2018.lesson001.demo20.ConfigBean$$EnhancerBySpringCGLIB$$dde45976@5e5d171f
bean名称:user1,别名:[],bean对象:com.javacode2018.lesson001.demo20.User@24313fcc
bean名称:user2Bean,别名:[],bean对象:com.javacode2018.lesson001.demo20.User@7d20d0b
bean名称:user3Bean,别名:[user3BeanAlias2, user3BeanAlias1],bean对象:com.javacode2018.lesson001.demo20.User@77f1baf5

上面的输出,我们主要关注与最后4行,前面的可以先忽略。

从输出中可以看出,有个名称为configBean的bean,正是ConfigBean这个类型,可以得出,被@Configuration修饰的类,也被注册到spring容器中了

最后3行输出就是几个User的bean对象了。

上面的用法应该很多人都比较熟悉,下面的属于重点了。

去掉@Configuration会怎样?

我们来看一下没有@Configuration的时候,什么效果。

新建一个ConfigBean1类

内容和ConfigBean类一样,只是将@Configuration注解去掉了,如下:

public class ConfigBean1 {

    //bean名称为方法默认值:user1
    @Bean
    public User user1() {
        return new User();
    }

    //bean名称通过value指定了:user2Bean
    @Bean("user2Bean")
    public User user2() {
        return new User();
    }

    //bean名称为:user3Bean,2个别名:[user3BeanAlias1,user3BeanAlias2]
    @Bean({"user3Bean", "user3BeanAlias1", "user3BeanAlias2"})
    public User user3() {
        return new User();
    }

}
来个测试用例test2

代码类似于test1,给spring容器传递ConfigBean1

@Test
public void test2() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConfigBean1.class);
    for (String beanName : context.getBeanDefinitionNames()) {
        //别名
        String[] aliases = context.getAliases(beanName);
        System.out.println(String.format("bean名称:%s,别名:%s,bean对象:%s",
                beanName,
                Arrays.asList(aliases),
                context.getBean(beanName)));
    }
}
运行输出
bean名称:org.springframework.context.annotation.internalConfigurationAnnotationProcessor,别名:[],bean对象:org.springframework.context.annotation.ConfigurationClassPostProcessor@333291e3
bean名称:org.springframework.context.annotation.internalAutowiredAnnotationProcessor,别名:[],bean对象:org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor@479d31f3
bean名称:org.springframework.context.annotation.internalCommonAnnotationProcessor,别名:[],bean对象:org.springframework.context.annotation.CommonAnnotationBeanPostProcessor@40ef3420
bean名称:org.springframework.context.event.internalEventListenerProcessor,别名:[],bean对象:org.springframework.context.event.EventListenerMethodProcessor@498d318c
bean名称:org.springframework.context.event.internalEventListenerFactory,别名:[],bean对象:org.springframework.context.event.DefaultEventListenerFactory@6e171cd7
bean名称:configBean1,别名:[],bean对象:com.javacode2018.lesson001.demo20.ConfigBean1@402bba4f
bean名称:user1,别名:[],bean对象:com.javacode2018.lesson001.demo20.User@795cd85e
bean名称:user2Bean,别名:[],bean对象:com.javacode2018.lesson001.demo20.User@59fd97a8
bean名称:user3Bean,别名:[user3BeanAlias2, user3BeanAlias1],bean对象:com.javacode2018.lesson001.demo20.User@f5ac9e4
分析结果

我们将2个输出的最后4行拿来对比一下:

有@Configuration注解的
bean名称:configBean,别名:[],bean对象:com.javacode2018.lesson001.demo20.ConfigBean$$EnhancerBySpringCGLIB$$dde45976@5e5d171f
bean名称:user1,别名:[],bean对象:com.javacode2018.lesson001.demo20.User@24313fcc
bean名称:user2Bean,别名:[],bean对象:com.javacode2018.lesson001.demo20.User@7d20d0b
bean名称:user3Bean,别名:[user3BeanAlias2, user3BeanAlias1],bean对象:com.javacode2018.lesson001.demo20.User@77f1baf5
没有@Configuration注解的
bean名称:configBean1,别名:[],bean对象:com.javacode2018.lesson001.demo20.ConfigBean1@402bba4f
bean名称:user1,别名:[],bean对象:com.javacode2018.lesson001.demo20.User@795cd85e
bean名称:user2Bean,别名:[],bean对象:com.javacode2018.lesson001.demo20.User@59fd97a8
bean名称:user3Bean,别名:[user3BeanAlias2, user3BeanAlias1],bean对象:com.javacode2018.lesson001.demo20.User@f5ac9e4
对比得出
  1. 对比最后3行,可以看出:有没有@Configuration注解,@Bean都会起效,都会将@Bean修饰的方法作为bean注册到容器中
  2. 两个内容的第一行有点不一样,被@Configuration修饰的bean最后输出的时候带有EnhancerBySpringCGLIB的字样,而没有@Configuration注解的bean没有Cglib的字样;有EnhancerBySpringCGLIB字样的说明这个bean被cglib处理过的,变成了一个代理对象。

目前为止我们还是看不出二者本质上的区别,继续向下看。

@Configuration加不加到底区别在哪?

通常情况下,bean之间是有依赖关系的,我们来创建个有依赖关系的bean,通过这个案例你就可以看出根本的区别了。

再来一个加@Configuration的案例

定义2个类。

ServiceA
package com.javacode2018.lesson001.demo20;

public class ServiceA {
}
ServiceB
package com.javacode2018.lesson001.demo20;

public class ServiceB {
    private ServiceA serviceA;

    public ServiceB(ServiceA serviceA) {
        this.serviceA = serviceA;
    }

    @Override
    public String toString() {
        return "ServiceB{" +
                "serviceA=" + serviceA +
                '}';
    }
}

上面定义了2个类,ServiceB依赖于ServiceA,ServiceB通过构造器注入ServiceA。

来个@Configuration类管理上面对象。

ConfigBean2
package com.javacode2018.lesson001.demo20;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ConfigBean2 {

    @Bean
    public ServiceA serviceA() {
        System.out.println("调用serviceA()方法"); //@0
        return new ServiceA();
    }

    @Bean
    ServiceB serviceB1() {
        System.out.println("调用serviceB1()方法");
        ServiceA serviceA = this.serviceA(); //@1
        return new ServiceB(serviceA);
    }

    @Bean
    ServiceB serviceB2() {
        System.out.println("调用serviceB2()方法");
        ServiceA serviceA = this.serviceA(); //@2
        return new ServiceB(serviceA);
    }

}

上面通过@Bean注解,向容器中注册了3个bean

注意@1和@2,通过this.serviceA()获取需要注入的ServiceA对象。

上面每个方法第一行都输出了一行日志。

重点关注一下@0这行日志会输出几次,大家先思考一下1次还是3次?

测试用例
@Test
public void test3() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConfigBean2.class);
    for (String beanName : context.getBeanDefinitionNames()) {
        //别名
        String[] aliases = context.getAliases(beanName);
        System.out.println(String.format("bean名称:%s,别名:%s,bean对象:%s",
                beanName,
                Arrays.asList(aliases),
                context.getBean(beanName)));
    }
}
运行输出

截取了几行输出如下:

调用serviceA()方法
调用serviceB1()方法
调用serviceB2()方法
bean名称:configBean2,别名:[],bean对象:com.javacode2018.lesson001.demo20.ConfigBean2$$EnhancerBySpringCGLIB$$ffa0178@77f1baf5
bean名称:serviceA,别名:[],bean对象:com.javacode2018.lesson001.demo20.ServiceA@41a2befb
bean名称:serviceB1,别名:[],bean对象:ServiceB{serviceA=com.javacode2018.lesson001.demo20.ServiceA@41a2befb}
bean名称:serviceB2,别名:[],bean对象:ServiceB{serviceA=com.javacode2018.lesson001.demo20.ServiceA@41a2befb}
分析结果

从输出中可以看出

  1. 前三行可以看出,被@Bean修饰的方法都只被调用了一次,这个很关键
  2. 最后三行中可以看出都是同一个ServiceA对象,都是ServiceA@41a2befb这个实例
这是为什么?

被@Configuration修饰的类,spring容器中会通过cglib给这个类创建一个代理,代理会拦截所有被@Bean修饰的方法,默认情况(bean为单例)下确保这些方法只被调用一次,从而确保这些bean是同一个bean,即单例的。

至于底层是如何实现的,可以去看一下公众号里面这篇文章:详解java中的动态代理和cglib代理。

现在各位应该感受到了,我写的文章前后一般都是有依赖的,所以也建议大家按顺序看,这样知识就是贯通的。

不加的案例

我们再来看看将ConfigBean2上的的@Configuration去掉,效果如何,代码就不写了,直接上输出结果:

调用serviceA()方法
调用serviceB1()方法
调用serviceA()方法
调用serviceB2()方法
调用serviceA()方法
bean名称:configBean2,别名:[],bean对象:com.javacode2018.lesson001.demo20.ConfigBean2@6e171cd7
bean名称:serviceA,别名:[],bean对象:com.javacode2018.lesson001.demo20.ServiceA@402bba4f
bean名称:serviceB1,别名:[],bean对象:ServiceB{serviceA=com.javacode2018.lesson001.demo20.ServiceA@795cd85e}
bean名称:serviceB2,别名:[],bean对象:ServiceB{serviceA=com.javacode2018.lesson001.demo20.ServiceA@59fd97a8}
结果分析
  1. serviceA()方法被调用了3次
  2. configBean2这个bean没有代理效果了
  3. 最后3行可以看出,几个ServiceA对象都是不一样的

spring这块的源码

spring中用下面这个类处理@Configuration这个注解:

org.springframework.context.annotation.ConfigurationClassPostProcessor

这里面重点关注这几个方法:

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) 
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) 

最后一个方法会创建cglib代理,大家可以设置断点进去看看,有问题欢迎交流。

总结

  1. 到目前为止加不加@Configuration注解,有什么区别,大家估计比我都清楚了
  2. @Configuration注解修饰的类,会被spring通过cglib做增强处理,通过cglib会生成一个代理对象,代理会拦截所有被@Bean注解修饰的方法,可以确保一些bean是单例的
  3. 不管@Bean所在的类上是否有@Configuration注解,都可以将@Bean修饰的方法作为一个bean注册到spring容器中

案例源码

链接:https://pan.baidu.com/s/1p6rcfKOeWQIVkuhVybzZmQ 
提取码:zr99

来源:https://mp.weixin.qq.com/s?__biz=MzA5MTkxMDQ4MQ==&mid=2648934137&idx=1&sn=3775d5d7a23c43616d1274b0b52a9f99&chksm=88621ec7bf1597d1b16d91cfb28e63bef485f10883c7ca30d09838667f65e3d214b9e1cebd47&token=1372043037&lang=zh_CN&scene=21#wechat_redirect

Spring进阶(十二)之@Configuration和@Bean详解 @Configration和@Bean注解详解 阅读详情

相关推荐

Spring注解之@Configration结合@Bean定义配置类

Spring注解之@Configration定义配置类 之前我们都是通过xml的方式定义bean,里面会写很多bean元素,然后spring启动的时候,就会读取bean xml配置文件,然后解析这些配置,然后会将这些bean注册到spring容器中,供使用者使用。 jdk1.5里面有了注解的功能,spring也没闲着,觉得注解挺好用的,就将注解加了进来,让我们通过注解的方式来定义bean,...

优快云_KONGlX的博客 898

SpringBoot如何批量注入Bean到Spring容器中?

目录 需求 实现 项目结构 待注入类 ClassScanner工具类 ListenerScan注解 BeanDefinitionRegister 配置文件 启动类 结果 需求 标题有些许拗口,容在下解释一二。 简单来说,就是实现mybatis框架中的MapperScan功能(接口扫描与代理对象注册)。 详细来说: 在Spring环境中,我们常通过XML文件 或者 @Controller、@Component、@Service、@Bean等注解进行bean的注册。 这么做比较简

小楼夜听雨的博客 3228

Ubuntu 上 1Panel 的安装与高效运维实践

本文详细介绍了在Ubuntu系统上安装和高效运维1Panel面板的完整实践指南。内容涵盖了一键安装、Docker容器可视化部署、计划任务自动化以及网站数据库管理等核心功能,并提供了安全加固、资源监控与数据备份等进阶技巧,旨在帮助用户快速搭建并管理一个强大易用的服务器环境。

weixin_29210759的博客 146

【spring 自动化配置】

例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。提示:以下是本篇文章正文内容,下面案例可供参考``System . out . println("使用 bean 2");System . out . println("使用 bean 1");} }

weixin_41622634的博客 448

避坑指南:STM32CubeMX安装后,你的第一个工程为什么中文全是乱码?

本文详细解析了STM32CubeMX安装后中文乱码问题的根源及解决方案。从诊断乱码现象到分析编码冲突背景,提供了新项目UTF-8化、旧项目GBK兼容及版本降级等多种实用方案,帮助开发者彻底解决这一常见问题。

weixin_30699955的博客 475

ROS专栏—基于STM32F103的INA219电源数据采集

文章主要记录了stm32f103对ina219的数据采集

热爱生活、奋斗前行 2357

【Java愚公】springboot通过配置文件动态生成多个bean

【代码】【Java愚公】springboot通过配置文件动态生成多个bean。

qq_38362283的博客 2515

如何利用CN3791实现太阳能电池板对锂电池的高效充电管理

本文详细介绍了如何利用CN3791芯片实现太阳能电池板对锂电池的高效充电管理。CN3791集成了MPPT(最大功率点跟踪)功能,能智能调节太阳能板的输出,确保在不同光照条件下获得最大功率。文章涵盖芯片工作原理、外围电路设计、充电全过程管理及实际应用经验,帮助开发者优化太阳能充电系统效率。

weixin_33709219的博客 500

Spring Bean 批量注册

文章目录@Configration和@Bean注解详解@ComponentScan、@ComponentScans详解@Import参考 @Configration和@Bean注解详解 @Configuration注解修饰的类,会被spring通过cglib做增强处理,通过cglib会生成一个代理对象,代理会拦截所有被@Bean注解修饰的方法,可以确保一些bean是单例的 不管@Bean所...

永无止境 1910

用 XCO 库一键找出某个 ABAP 类的全部子类

ABAP XCO库子类枚举技术解析 本文介绍了在ABAP项目中如何利用XCO库高效获取类的继承层次结构。传统方法使用CL_ABAP_CLASSDESCR或手动维护映射表存在效率低、易遗漏的问题。新方法通过XCO库的IF_XCO_AO_CLASS接口,可简洁地获取父类的所有子类(包括间接子类)。 核心API链式调用: 获取类句柄:xco_cp_abap=>class() 导航子类集合:subclasses->all 获取结果:get()返回类引用表或get_names()返回类名列表 典型应用场景

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 130

2021年全网最细 VirtualBox 虚拟机安装 Ubuntu 20.04.2.0 LTS及Ubuntu的相关配置

目录一、VirtualBox 虚拟机的安装1. VirtualBox 的下载和安装2. 设置 VirtualBox 存储文件夹3. 在 VirtualBox 创建虚拟机二、Linux 操作系统(Ubuntu)的安装1. Linux 操作系统(Ubuntu)的下载2. 安装 Ubuntu3. 启动 Ubuntu三、配置 Ubuntu1. 设置终端2. 设置共享剪贴板3. 设置共享文件夹 一、VirtualBox 虚拟机的安装 VirtualBox 是由德国 Innotek 公司开发,由 Sun Microsy

XAMO Lab|代码、调试与复盘笔记 2万+

Spring:如何使用BeanFactoryPostProcessor创建多个Bean

如何使用BeanFactoryPostProcessor创建多个Bean

永远保持随时离开的技术能力! 837

RAGFlow升级指南(纯小白都看得懂)

升级背景:RAGFlow项目原来的版本是0.17.0版本,在使用过程中,发现当知识库检索为空的时候并且使用到rerank模型的时候,就会输出错误的信息;为了解决这个版本问题,特意升级到最新的版本0.17.2(截止2025-3-14时最新版本就是0.17.2了)官方升级文档https://ragflow.io/docs/dev/upgrade_ragflow官方文档对小白还是不太友好,作者也是捣鼓了十多分钟,特出下面的升级指南前提:旧版本的RAGFlow项目是启动好了的1.在ragflow目录下执行(拉取最新

Ven%的博客 3597

spring成神之路第十七篇:@Configration 和@Bean 注解详解(bean 批量注册)

上次去头条面试: 面试官:spring中,类上加不加@Configuration注解,有什么区别? 我:当某个类上有@Configuration注解的时候,可以在这个类中使用@Bean注解向spring容器中注册bean;如果不加@Configuration注解,不能通过@Bean注解注册bean。 面试官:你确定不用@Configuration注解,不能通过@Bean注解来注册bean? 我:...

优快云_KONGlX的博客 190

【ComfyUI】Wan2.2 + IndexTTS 图像数字人或动物口播视频生成

本文介绍了一个基于ComfyUI的数字人口播视频生成工作流,整合了IndexTTS和图像处理技术。该系统通过多模型协同工作,实现从形象图、文本和音频输入到自动生成口播视频的全流程。核心包含WanVideo系列模型,通过CLIP Vision、T5文本编码器和Wav2Vec语音模型分别处理视觉特征、语义理解和口型同步。工作流涵盖素材加载、特征提取、音频处理和视频生成等节点,支持人物、动物等多种主体的口播内容创作。该方案自动化程度高,适用于知识讲解、剧情旁白等多种场景,能帮助创作者高效产出高质量口播视频。

Mr数据杨 2063

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

Spring系列之@Configration和@Bean注解详解(bean批量注册)

上次去头条面试: 面试官:spring中,类上加不加@Configuration注解,有什么区别? 我:当某个类上有@Configuration注解的时候,可以在这个类中使用@Bean注解向spring容器中注册bean;如果不加@Configuration注解,不能通过@Bean注解注册bean。 面试官:你确定不用@Configuration注解,不能通过@Bean注解来注册bean? 我:看着面试官,犹豫了10秒钟,说:不加@Configuration通过@Bean注解也可以注册bean 面

azhou的代码园 2165

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Spring系列第17篇:@Configration和@Bean注解详解(bean批量注册)

使用步骤:在类上使用注解通过容器来加注解修饰的类到目前为止加不加@Configuration注解,有什么区别,大家估计比我都清楚了@Configuration注解修饰的类,会被spring通过cglib做增强处理,通过cglib会生成一个代理对象,代理会拦截所有被@Bean注解修饰的方法,可以确保一些bean是单例的不管@Bean所在的类上是否有@Configuration注解,都可以将@Bean修饰的方法作为一个bean注册到spring容器中。

GitHub质检员 454

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

Spring @Configration和@Bean注解

Spring @Configration和@Bean注解在面试常见场景 Q: spring中,类上加不加@Configuration注解,有什么区别? A: 当某个类上有@Configuration注解的时候,可以在这个类中使用@Bean注解向spring容器中注册bean;如果不加@Configuration注解,不能通过@Bean注解注册bean。 Q: 你确定不用@Configuration注解,不能通过@Bean注解来注册bean? A: 看着面试官,犹豫了10秒钟,说:不加@Configurat

ylx1066863710的博客 854

Spring系列第17篇:@Configration和@Bean注解(1)

使用步骤:在类上使用注解通过容器来加注解修饰的类@Bean注解。

2301_82244389的博客 724

夯实spring(十七): @Configration、@Bean注解详解

Configuration注解修饰的类,会被spring通过cglib做增强处理,通过cglib会生成一个代理对象,代理会拦截所有被@Bean注解修饰的方法,可以确保一些bean是单例的不管@Bean所在的类上是否有@Configuration注解,都可以将@Bean修饰的方法作为一个bean注册到spring容器中。

hjji12的博客 1165

Spring第17篇:@Configration和@Bean解密

@Configuration注解 用法 @Configuration这个注解可以加在类上,让这个类的功能等同于一个bean xml配置文件,如下: @Configuration publicclassConfigBean{ } 上面代码类似于下面的xml: <?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="http://www.springframework.org/schema/beans" x...

chenzoff的专栏 296

spring 中的bean和@Bean

一.Spring bean定义   由Spring IoC容器所管理的对象称为bean。bean被实例化,组装,并通过Spring IoC容器所管理的对象。Bean配置信息定义了Bean的实现及依赖关系,Spring容器根据各种形式的Bean配置信息在容器内部建立Bean定义注册表,然后根据注册表加载、实例化Bean,并建立Bean和Bean的依赖关系,最后将这些准备就绪的Bean放到Bean缓存池中,以供外层的应用程序进行调用。 bean 就是spring管理的对象 二.对bean的理解 1.Java

weixin_42408447的博客 453

12.Spring Bean是什么

Bean在Spring和SpringMVC中无所不在,将这个概念内化很重要,下面分享一下我的想法: 一、Bean是啥1、Java面向对象,对象有方法和属性,那么就需要对象实例来调用方法和属性(即实例化); 2、凡是有方法或属性的类都需要实例化,这样才能具象化去使用这些方法和属性; 3、规律:凡是子类及带有方法或属性的类都要加上注册Bean到Spring IoC的注解;(@Component , @...

郑学炜的技术博客 1万+
上一篇: Spring成神之路第十六篇:深入理解 java 注解及 spring 对注解的增强(预备知识)
下一篇: Spring成神之路第十八篇:@ComponentScan、@ComponentScans 详解(bean 批量注册)
码趣资源网
博客等级 码龄4年 269粉丝 518原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值