目录
Spring会帮助我们创建bean,那么它底层是调用什么方法进行创建的呢?有以下三种方法
- 使用构造方法
- 使用工厂类方法
- 使用工厂类的静态方法
接下来详细讲解这三种方法。
Spring默认使用类的空参构造方法创建bean,假如类没有空参构造方法,将无法完成bean的创建,接下来我们可以测试一下。
package com.example.dao;
import com.example.pojo.Student;
public class StudentDaoImpl1 implements StudentDao{
/*public StudentDaoImpl1() {
}*/
public StudentDaoImpl1(int a){};
@Override
public Student findById(int id){
return new Student(id,"程序员","北京");
}
}

错误原因:Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'studentDao' defined in class path resource [bean.xml]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'int' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
翻译:上下文初始化过程中遇到异常-取消刷新尝试:org.springframework.beans.factory.UnsatisfiedDependencyException:创建类路径资源[bean.xml]中定义的名称为“studentDao”的bean时出错:通过构造函数参数0表示的不满足依赖关系;嵌套异常为org.springframework.beans.factory.NoSuchBeanDefinitionException:没有可用的类型为“int”的符合条件的bean:应至少有1个符合自动连线候选条件的bean。依赖项注释:{}
其实就是没有空的构造函数,加上一个就好了
Spring可以调用工厂类的方法创建bean:创建工厂类,工厂类提供创建对象的方法,在配置文件中配置创建bean的方式为工厂方式。
工厂类StudentDaoFactory:
package com.example.dao;
public class StudentDaoFactory {
public StudentDao getStudentDao(){
return new StudentDaoImpl1(1);
}
}
bean.xml的配置:
<!-- id: 工厂对象的id,class:工厂类 -->
<bean id="studentDaoFactory" class="com.example.dao.StudentDaoFactory" />
<!-- id:bean对象的id,factory-bean:工厂对象的id,factory-method:工厂方法 -->
<bean id="studentDao" factory-bean="studentDaoFactory" factory-method="getStudentDao"></bean>
测试方法:
@Test
public void t2(){
// 创建spring容器
ApplicationContext ac = new FileSystemXmlApplicationContext("C:\\JavaProjects\\06SSM_Projects\\springdemo\\spring_ioc1\\src\\main\\resources\\bean.xml");
// 从容器中获取对象
StudentDao userDao = ac.getBean("studentDao",StudentDao.class);
System.out.println(userDao);
System.out.println(userDao.findById(1));;
}
测试结果:

OK,确实成功写出来了
Spring可以调用工厂类的静态方法创建bean,创建工厂类,工厂提供创建对象的静态方法,在配置文件中配置创建bean的方式为工厂静态方法。
工厂类StudentDaoFactory2
package com.example.dao;
public class StudentDaoFactory2 {
public static StudentDao getStudentDao2() {
return new StudentDaoImpl2();
}
}
bean.xml的配置
<!-- id:bean的id class:工厂全类名 factory-method:工厂静态方法 -->
<bean id="studentDao" class="com.example.dao.StudentDaoFactory2" factory-method="getStudentDao2"/>

都是可以成功运行的。
scope属性设置对象的创建策略。Spring通过配置 <bean> 中的 scope 属性设置对象的创建策略,共有两种种创建策略。
singleton:单例,默认策略。整个项目只会创建一个对象,通过 <bean> 中的 lazy-init 属性可以设置单例对象的创建时机:lazy-init="false"(默认):立即创建,在容器启动时会创建配置文件中的所有Bean对象。lazy-init="true":延迟创建,第一次使用Bean对象时才会创建。下面测试获取对象后的哈希值是否一样就可以知道是否配置单例策略了
bean.xml的配置
<bean id="studentDao" class="com.example.dao.StudentDaoImpl2" scope="singleton" lazy-init="true" />
测试方法
@Test
public void t3(){
// 创建Spring容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// 从容器获取对象
StudentDao studentDao1 = ac.getBean("studentDao",StudentDao.class);
StudentDao studentDao2 = ac.getBean("studentDao",StudentDao.class);
StudentDao studentDao3 = ac.getBean("studentDao",StudentDao.class);
System.out.println(studentDao1.hashCode());
System.out.println(studentDao2.hashCode());
System.out.println(studentDao3.hashCode());
}
运行结果

OK,得到的对象都是同一个哈希值,说明确实是同一个对象也就是说成功配置了单例模式。
prototype:多例,每次从容器中获取时都会创建对象。
bean.xml配置
<!-- 配置多例策略 -->
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2" scope="prototype"></bean>
测试结果

得到的哈希值不一样,说明得到的是不同的对象,确实是多例策略 。
request:每次请求创建一个对象,只在web环境有效。
session:每次会话创建一个对象,只在web环境有效。
gloabal-session:一次集群环境的会话创建一个对象,只在web环境有效。
对象的创建策略不同,销毁时机也不同:
- singleton:对象随着容器的销毁而销毁。
- prototype:使用JAVA垃圾回收机制销毁对象。
- request:当处理请求结束,bean实例将被销毁。
- session:当HTTP Session最终被废弃的时候,bean也会被销毁掉。
- gloabal-session:集群环境下的session销毁,bean实例也将被销毁。
Bean对象的生命周期包含创建——使用——销毁,Spring可以配置Bean对象在创建和销毁时自动执行的方法:
在StudentDaoImpl2中新增生命周期方法
// 创建时自动执行的方法
public void init(){
System.out.println("使用StudentDaoImpl2创建对象"+this.hashCode());
}
// 销毁时自动执行的方法
public void destroy(){
System.out.println("销毁StudentDaoImpl2创建的对象"+this.hashCode());
}
<!-- init-method:创建对象时执行的方法 destroy-method:销毁对象时执行的方法 -->
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2" scope="singleton" init-method="init" destroy-method="destory"></bean>
测试方法
@Test
public void t3(){
// 创建Spring容器
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean1.xml");
// 销毁Spring容器,ClassPathXmlApplicationContext才有销毁容器的方法
ac.close();
}
测试结果

也确实可以
获取对象的时候是这样:
StudentDao studentDao = (StudentDao) ac.getBean("studentDao");
获取对象的时候是这样:
StudentDao studentDao2 = ac.getBean(StudentDao.class);不需要进行类型强转
虽然使用类型获取不需要强转,但如果在容器中有一个接口的多个实现类对象,则获取时会报错,此时需要使用类型+id/name获取,获取对象是这样:
StudentDao studentDao2 = ac.getBean("studentDao",StudentDao.class);
大家如果对于本期内容有什么不了解的话也可以去看看往期的内容,下面列出了博主往期精心制作的Maven,Mybatis等专栏系列文章,走过路过不要错过哎!如果对您有所帮助的话就点点赞,收藏一下啪。其中Spring专栏有些正在更,所以无法查看,但是当博主全部更完之后就可以看啦。
| Maven系列专栏 | Maven工程开发 |
| Maven聚合开发【实例详解---5555字】 |
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
如何使用RSpec::Core::RakeTask初始化RSpecRake任务?require'rspec/core/rake_task'RSpec::Core::RakeTask.newdo|t|#whatdoIputinhere?endInitialize函数记录在http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#initialize-instance_method没有很好的记录;它只是说:-(RakeTask)initialize(*args,&task_block)AnewinstanceofRake