1. 程式人生 > >Bean的裝配方式--註解裝配

Bean的裝配方式--註解裝配

1、
UserDao介面

public interface UserDao {
   public void save();
}

UserDaoImpl類

/*
相當於配置<bean id="userDao" class="link.UserDaoImpl" />
 */
@Repository("userDao")
public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println("userDao save");
    }
}

2、

UserService介面

public interface UserService {
  public void save();
}

UserServiceImpl類

/*
 * <bean id="userService" class="link.UserServiceImpl" >
 *    <property  name=""userDao ref="userDao" />
 * </bean>
 */

@Repository("userService")
public class UserServiceImpl implements UserService {   
    @Resource
(name="userDao") private UserDao userDao; public void setUserDao(UserDao userDao){ this.userDao=userDao; } public void save() { this.userDao.save(); System.out.println("userService save"); } }

3、

UserAction類

/**
 * <bean id="userAction" class="link.UserAction">
 *    <property  name=""userService" ref="userService" />
 * </bean>
 */
@Controller("userAction") public class UserAction{ @Resource(name="userService") private UserService userService; public void setUserService(UserService userService){ this.userService=userService; } public void save(){ this.userService.save(); System.out.println("userAction save"); } }

4、

Test類

public class Test {
  public static void main(String[] args) {
      new Test().test();
  }
  public void test(){
      String xmlPath="link/bean.xml";
      ApplicationContext applicationContext=new   ClassPathXmlApplicationContext(xmlPath);

      UserAction userAction=(UserAction)applicationContext.getBean("userAction");
      System.out.println(userAction);
      userAction.save();
  }
}

7、bean.xml配置檔案

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">


     <!-- 註解解析 -->
        <context:component-scan base-package="link"/>
</beans>

@Resource 相當於xml中的property,@Repository\@Service\@Constroller類似bean