springBean初始化⽅法:⽆参构造、有参构造、set注⼊Bean初始化
1.Bean的初始化⽅式:
1.⽆参构造(默认构造⽅法);
2.有参构造(⾃定义构造⽅法);
3.set⽅法
2.例⼦
2.1新建⼀个空的spring项⽬
其中:
client包是主⽅法所在类的包;
domain包是实体Bean的包;
resource包是xml配置⽂件所在的包;
readme是项⽬介绍。
2.2类⽂件创建
2.3java⽂件
import t.ApplicationContext;
import t.support.ClassPathXmlApplicationContext; import domain.People;
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext( "resource/*l");
People people = (People) Bean("people");
people.say();
applicationContext = new ClassPathXmlApplicationContext(
"resource/*No.xml");
people = (People) Bean("people");
people.say();
applicationContext = new ClassPathXmlApplicationContext(
"resource/*l");
people = (People) Bean("people");
people.say();
}
}
import java.io.Serializable;
public class People implements Serializable{
/**
*
*/
private static final long serialVersionUID = -3290777865940655640L;
private String name;
private String age;java接口有没有构造方法
public void say(){
System.out.println("say");
}
public People(String name,String age){
this.name = name;
this.age = age;
System.out.Class()+"有参构造");
}
public People(){
System.out.Class()+"⽆参构造");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
2.4xml⽂件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/schema/beans /schema/beans/spring-beans.xsd">
<bean id="people" class="domain.People">
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/schema/beans
/schema/beans/spring-beans.xsd">
<bean id="people" class="domain.People">
<property name="name">
<value>xiaojua</value>
</property>
<property name="age">
<value>23</value>
</property>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/schema/beans
/schema/beans/spring-beans.xsd">
<bean id="people" class="domain.People">
<constructor-arg name="name" type="java.lang.String">
<value>xiaoming</value>
</constructor-arg>
<constructor-arg name="age" type="java.lang.String">
<value>12</value>
</constructor-arg>
</bean>
</beans>
2.5运⾏结果
class domain.People有参构造
say
class domain.People⽆参构造
say
class domain.People⽆参构造
say
3.总结
JavaBean的初始化默认使⽤默认的构造⽅法,所以,如果某些操作必须在类加载时完成,可以使⽤显⽰的默认⽆参构造⽅法中完成,否则会使⽤隐式的默认⽆参构造。
这个项⽬实现不同的bean⽂件配置以及使⽤不同的⽅式初始化
使⽤⽆参构造⽅法,
有参构造
set⽅法
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论