熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

spring用annotation-autowire配置

2022-06-13   來源: Java開源技術 

  <?xml version= encoding=UTF?>

  <beans xmlns=

  xmlns:xsi=instance

  xmlns:p=

  xsi:schemaLocation=

  beansxsd

  

  contextxsd

  xmlns:context= ><! 使用annotation需加上面三行的該內容和下面的一行 >

  <context:annotationconfig/>

  <bean id=u class=annotationautoWireUserDAOImpl>

  </bean>

  <bean id=u class=annotationautoWireUserDAOImpl>

  </bean>

  <bean id=userService class=annotationautoWireUserService>

  </bean>

  </beans>

  Userjava

  package annotationautoWire;

  public class User {

  private String username;

  private String password;

  public String getUsername() {

  return username;

  }

  public void setUsername(String username) {

  thisusername = username;

  }

  public String getPassword() {

  return password;

  }

  public void setPassword(String password) {

  thispassword = password;

  }

  }

  UserDAOjava

  package annotationautoWire;

  public interface UserDAO {

  public void save(User user)

  }

  UserDAOImpljava

  package annotationautoWire;

  public class UserDAOImpl implements UserDAO {

  public void save(User user) {

  Systemoutprintln(user saved!

  }

  }

  UserServicejava

  package annotationautoWire;

  import orgspringframeworkbeansfactoryannotationAutowired;

  import orgspringframeworkbeansfactoryannotationQualifier;

  public class UserService {

  private UserDAO userDAO;

  public void init() {

  Systemoutprintln(init

  }

  public void add(User user) {

  userDAOsave(user)

  }

  public UserDAO getUserDAO() {

  return userDAO;

  }

  @Autowired//需配置在setter方法上

  public void setUserDAO(@Qualifier(u) UserDAO userDAO) {

  thisuserDAO = userDAO;

  }

  public void destroy() {

  Systemoutprintln(destroy

  }

  }

  UserServiceTestjava

  package annotationautoWire;

  import orgjunitTest;

  import orgntextApplicationContext;

  import orgntextsupportClassPathXmlApplicationContext;

  public class UserServiceTest {

  @Test

  public void testAnnotationAutoWire() throws Exception {

  ApplicationContext ctx = new ClassPathXmlApplicationContext(annotation/autoWire/annotationAutoWirexml

  UserService service = (UserService)ctxgetBean(userService

  serviceadd(new User())

  Systemoutprintln(servicegetUserDAO())

  }

  }


From:http://tw.wingwit.com/Article/program/Java/ky/201311/28149.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.