Spring instantiates javabeans in three ways
- 2020-04-01 02:24:41
- OfStack
The first is to configure the javabean file directly
XML beans.
<bean id="sayhello" class="test.service.impl.HelloBean"/>
PersonDao. Java
package springdao;
public class personDao {
private String name;
private String dep;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDep() {
return dep;
}
public void setDep(String dep) {
this.dep = dep;
}
public void Test(){
System.out.println("hello,spring");
}
}
springtest.java
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"beans.xml"});
personDao pe=(personDao)ctx.getBean("persondao");//By configuring javabeans & NBSP;
}
The second: XML configuration +factory class, instantiated using static factory methods
XML beans.
<bean id="productCreator" class="serviceImpl.productCreator" factory-method="createPersonDao"></bean>
ProductCreator. Java
package serviceImpl;
import springdao.personDao;
public class productCreator {
public static personDao createPersonDao(){
return new personDao();
}
public personDao productAcreate(){
return new personDao();
}
}
springtest.java
personDao pe=(personDao)ctx.getBean("productCreator");
pe.test();
PersonDao, Java same method one file
@note: the red part must be defined with the static keyword
3. XML configuration +factory class, instantiated using the instance factory method
XML beans.
<bean id="productCreator" class="serviceImpl.productCreator"/>
<bean id="productAcreate" factory-bean="productCreator" factory-method="productAcreate"/>
Springtest. Java
personDao pe=(personDao)ctx.getBean("productAcreate");//Instantiate the bean file by configuring the instance factory method
pe.test();
The productCreator. Java and persondao.java files are the same as above