码迷,mamicode.com
首页 > 编程语言 > 详细

Spring通过注解配置Bean

时间:2017-08-14 09:59:22      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:sys   pat   存在   display   utf-8   autowired   red   classpath   get   

@Component: 基本注解, 标识了一个受 Spring 管理的组件
@Repository: 标识持久层组件
@Service: 标识服务层(业务层)组件
@Controller: 标识表现层组件

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 配置自动扫描的包: 需要加入 aop 对应的 jar 包 -->
    <!-- 扫描此包及此包下的子包 -->
    <context:component-scan base-package="com.spring.annotation"></context:component-scan>

</beans>

demo

技术分享
package com.spring.annotation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;

@Controller
public class UserAction {
    
    /*默认情况下所有使用 @Authwired 注解的属性都需要被设置. 当 Spring 找不到匹配的 Bean 装配属性时,
    会抛出异常, 若某一属性允许不被设置, 可以设置 @Authwired 注解的 required 属性为 false
    默认情况下, 当 IOC 容器里存在多个类型兼容的 Bean 时, 通过类型的自动装配将无法工作. 
    此时可以在 @Qualifier 注解里提供 Bean 的名称. Spring 允许对方法的入参标注 
    @Qualifiter 已指定注入 Bean 的名称*/
    
    @Autowired(required=false)
    @Qualifier("usreService")
    private UsreService usreService;
    
    public void execute(){
        System.out.println("添加用户");
        usreService.add();
    }
    
}


package com.spring.annotation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UsreService {
    
    @Autowired
    private UserRepository userDao;
    
    public void add(){
        System.out.println("接收请求");
        userDao.save();
    }
    
}



package com.spring.annotation;

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository {
    
    public void save(){
        System.out.println("保存数据");
    }
    
}
View Code

 测试

技术分享
package com.spring.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    
    public static void main(String[] args) {
        
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annotation.xml");
        
        UserAction userAction = (UserAction) ctx.getBean("userAction");//默认Bean id为类名首字母小写
        userAction.execute();
    }
    
}
View Code

 

Spring通过注解配置Bean

标签:sys   pat   存在   display   utf-8   autowired   red   classpath   get   

原文地址:http://www.cnblogs.com/lusufei/p/7355812.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!