Spring 实例化bean的三种方式:

方法一:使用构造器实例化bean

java代码:

package com.model;

public class User {

    private String username;

    public User(){

    }

    public User(String username){
this.setUsername(username);
} public void sayHello(){
System.out.println("hello ");
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
}
}

配置文件:

 <!--方法一:使用构造器实例化bean  -->
<bean id="user" class="com.model.User"></bean>

测试代码:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
//方法一:使用构造器实例化bean
User user = (User)applicationContext.getBean("user");
user.sayHello();

方法二:使用静态工厂方法实例化bean
java代码:

package com.test;

public class StaticFactory {

    private static StaticFactory staticFactory  = new StaticFactory();
public static StaticFactory getBean() {
return staticFactory;
} public void say() {
System.out.println("new Instance!");
}
}

配置文件:

<!--方法二:使用静态工厂方法实例化bean  -->
<bean id="staticFactory" class="com.test.StaticFactory" factory-method="getBean"/>

测试代码:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});

        //方法二:使用静态工厂方法实例化bean
StaticFactory staticFactory = (StaticFactory)applicationContext.getBean("staticFactory");
staticFactory.say();

方法三:使用实例工厂方法实例化bean

java代码:

package com.test;

import com.dao.UserDao;
import com.dao.impl.UserDaoImpl; public class InstanceBean {
private static UserDao userDaoA = new UserDaoImpl(); //该方法必须是非静态的
public UserDao getBeanInstance() {
return userDaoA;
} }
接口UserDao:
package com.dao; import com.model.User; public interface UserDao {
public void add(User user);
public void findByid(String id);
} 实现类UserDaoImpl:
package com.dao.impl; import com.dao.UserDao;
import com.model.User; public class UserDaoImpl implements UserDao { private String hello;
@Override
public void add(User user) {
System.out.println("方法三:qwqwqwq!!!");
} @Override
public void findByid(String id) { } public String getHello() {
return hello;
} public void setHello(String hello) {
this.hello = hello;
} }

配置文件:

<!--方法三:使用实例工厂方法实例化bean  -->
<bean id="instanceBean" class="com.test.InstanceBean"/>
<bean id="userDaoA" factory-bean="instanceBean" factory-method="getBeanInstance"></bean>

测试代码:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
//方法三:使用实例工厂方法实例化bean
UserDao userDao = (UserDao)applicationContext.getBean("userDao");
String username = "pppp";
userDao.add(new User(username));
上一篇:springmvc 请求出现400错误(当传入的参数类型是Date时加上下面代码试试)


下一篇:使用visual studio 2013 快速搭建phonegap开发环境