spring bean依赖与配置
生活随笔
收集整理的這篇文章主要介紹了
spring bean依赖与配置
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一個最基本的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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/aophttp://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>
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種作用域,有時間再深入細聊。
總結
以上是生活随笔為你收集整理的spring bean依赖与配置的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring 三种注入方式
- 下一篇: 单细胞测序 doublet 二聚体