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);
    }
  • 相关阅读:
    根据中国气象局提供的API接口实现天气查询
    小程序——云函数发送请求
    apifm-wxapi API工厂
    首次使用 linux 阿里云服务器,入门及使用
    Android立体旋转动画实现与封装(支持以X、Y、Z三个轴为轴心旋转)
    Android来电监听和去电监听
    Android 源码下载方法(Git 方式clone)
    HandlerThread 创建一个异步的后台线程
    Android Toast cancel和show 不踩中不会知道的坑
    PopupWindow 点击外部和返回键无法消失背后的真相(setBackgroundDrawable(Drawable background))
  • 原文地址:https://www.cnblogs.com/huey/p/4508873.html
Copyright © 2011-2022 走看看