一个最基本的bean
public class User {
private String username;
private String password;
public String getUsername()
{
return this.username;
}
public void setUsername(String name)
{
this.username = name;
}
public String getPassword()
{
return this.password;
}
public void setPassword(String password)
{
this.password = password;
}
}
接着在一个类中创建spring 容器:
ClassPathXmlApplicationContextctx =
new ClassPathXmlApplicationContext("beans.xml");
stx.getBean("xxxxxxxx");
在beans.xml中最基本的配置
1.<property>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 注册一个 UserDAOImpl 对象实例-->
<bean id="u" class="com.deciphering.User">
<property name="usrname" value="kack"></property>
<property name="password" value="123"></property>
</bean>
</beans>
2.配合setter方法 使用 <ref>
<bean id="userService" class="com.deciphering.dao.service.UserServiceImpl">
<!-- 构造方式 将UserDAOImpl u 对象实例 注入到 UserServiceImpl 中的userDAO -->
<property name="userDAO">
<ref bean="u">
</property>
</bean>
3.配合构造方法,<constructor-arg>使用
<!-- 注册一个 UserServiceImpl 对象实例-->
<bean id="userService" class="com.deciphering.dao.service.UserServiceImpl">
<!-- 构造方式 将UserDAOImpl u 对象实例 注入到 UserServiceImpl 中的userDAO -->
<constructor-arg >
<ref bean="u">
</constructor-arg>
</bean>
public class UserServiceImpl implements UserService
{
private UserDAO userDAO;
public UserServiceImpl(UserDAO userDAO)
{
super();
this.UserDAO = UserDAO;
}
public void add(User user)
{
userDAO.save(user);
}
public UserDAO getUserDAO()
{
return this.userDAO
}
public void setUserDAO(UserDAO userDAO)
{
this.userDAO = userDAO;
}
4.集合注入
public class User {
private Set<String> sets;
private List<String> list;
private Map<String,String> maps;
}
bean里面含有集合
<property name="sets">
<set>
<value>1</value>
<value>2</value>
<value>3</value>
</set>
</property>
<property name="list">
<list>
<value>1</value>
<value>2</value>
<value>3</value>
</list>
</property>
<property name="maps">
<map>
<entry key="1" value="1"></entry>
<entry key="2" value="2"></entry>
<entry key="3" value="3"></entry>
</map>
</property>
分别是set list map集合 设置数据
spring中的beans有不同的生命周期和作用于,在spring3.0中已经扩展到5种作用域,有时间再深入细聊。