Spring的bean创建方式ref使用方法

 

 

Spring的bean创建方式ref使用方法

 

 

 java

public class UserServiceImp implements UserService{
    private UserDao userDao =null;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    @Override
    public void getUser() {
        // TODO Auto-generated method stub
        userDao.getUser();
    }

}

bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
        <!-- bean 就是java对象  有spring容器创建和管理 -->
<!--    <bean id="hello" name="cn.ioc.bean.hello">
            <property name="name" value="张三"></property>
        </bean>  -->
        <bean name="userdao" class="cn.ioc.dao.imp.UserDaoImp"></bean> 
          <bean name="othersql" class="cn.ioc.dao.imp.UserOtherSqlImp"></bean>
          <bean name="service" class="cn.ioc.service.imp.UserServiceImp">
              <property name="userDao" ref="userdao"></property>
          </bean>
          <bean name="services" class="cn.ioc.service.imp.UserServiceImp">
              <property name="userDao" ref="othersql"></property>
          </bean>
</beans>

test

public class Test {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        UserServiceImp usi = (UserServiceImp) ac.getBean("service");
        usi.getUser();
        UserServiceImp usis = (UserServiceImp) ac.getBean("services");
        usis.getUser();
    }
}

 

上一篇:Spring——MyBatis整合


下一篇:数据库不重复页面友好提示优化方案