zoukankan      html  css  js  c++  java
  • Spring

    除了基于 XML 的配置外,Spring 也支持基于 Annotation 的配置。Spring 提供以下介个 Annotation 来标注 Spring Bean:
      @Component:标注一个普通的 Spring Bean
      @Controller:标注一个控制器组件类
      @Service:标注一个业务逻辑组件类
      @Repository:标注一个 DAO 组件类

    基于 Annotation 配置的示例

    DAO 组件以 @Repository 标注:

    public interface UserDao {
        public User getUserByUsername(String username);
    }
    
    @Repository(
    "userDao") public class UserDaoImpl implements UserDao { List<User> users = new ArrayList<User>(); public UserDaoImpl() { users.add(new User(1001, "huey", "123")); users.add(new User(1002, "tmac", "abc")); users.add(new User(1003, "suer", "xxx")); } public User getUserByUsername(String username) { for (User user : users) { if (username.equals(user.getUsername())) { return user; } } return null; } }

    业务逻辑组件以 @Service 标注:

    public interface UserServ {    
        public User queryUserByUsername(String username);    
    }
    
    @Service(
    "userServ") public class UserServImpl implements UserServ { @Resource(name="userDao") private UserDao userDao; public User queryUserByUsername(String username) { return userDao.getUserByUsername(username); } }

    Spring 配置文件,无需配置 Bean,但须配置 <context:component-scan/>:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        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">
        
        <!-- 自动扫描指定包及其子包下的所有 Bean 类 -->
        <context:component-scan base-package="com.huey.dream" />
    </beans>

    测试方法:

    @Test
    public void testAnnotation() throws Exception {
        ApplicationContext appCtx =  
            new ClassPathXmlApplicationContext("applicationContext.xml");
        UserServ userServ = appCtx.getBean("userServ", UserServ.class);
        
        String username = "huey";
        User user = userServ.queryUserByUsername(username);
        System.out.println(user);
    }
  • 相关阅读:
    利用xslt合并多个xml文件到一个文件
    如果利用网络推广老家的特产水果?
    C#并行编程中的Parallel.Invoke
    Asp.Net MVC实现优酷(youku)Web的上传
    修改用户名后TSF出现"需要本地工作区。工作区 xxx 并未驻留在本计算机上"
    JS浏览器滚轮事件实现横向滚动照片展
    Android实现dialog时候弹出软键盘dialog移位问题
    快速搭建多线程Windows服务解决方案
    Difference between WCF and Web API and WCF REST and Web Service
    WPF应用程序的性能提升(一)
  • 原文地址:https://www.cnblogs.com/huey/p/4508873.html
Copyright © 2011-2022 走看看