基于注解方式配置bean以及自动转配属性

在classpath中扫描bean组件

组件包括

》@Component:基本注解,标识一个受spring管理的bean组件

》@Controller:标识控制层bean组件

》@service:标识业务层bean组件

》@Repository:标识持久层bean组件,也就是dao层

》@Autowired:自动装配(相当于new了一个)

还有@Resouce、@inject这里就不做一一讲解了。

对扫描到的组件有默认的命名策略类,也就是驼峰命名规则。

比如在class PwqFcxz类上面加一个@Component,那么这个bean的id为pwqFcxz。

也可以不使用默认命名,使用value值,自己命名如:@Controller(value="qwe"),那么要获得这个class时,就要使用qwe获得

下面写上实例代码:

创建一个名为spring4-2-test的web项目

目录结构如下

MyController为控制层,Myservice为业务层,MyDao为持久层,Person为实体类,ScanMain为测试类,applicationcontext-scan.xml为全局配置文件,lib为导入的jar。

Person为实体类:

package com.spring.beans.scan;

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

@Repository
public class MyDao {
    @Autowired
    Person person;
    public void insert() {
        person.say();
        System.out.println("在数据库中添加成功");
    }
}
 

MyController为控制层:

package com.spring.beans.scan;

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

@Controller
public class MyController {
    @Autowired
    MyService service;
    public void execute() {
        service.insert();
    }
    
}
 

Myservice为业务层:

package com.spring.beans.scan;

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

@Service
public class MyService {
    @Autowired
    MyDao dao;
    public void insert() {
        dao.insert();
    } 
}
 

MyDao为持久层:

package com.spring.beans.scan;

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

@Repository
public class MyDao {
    @Autowired
    Person person;
    public void insert() {
        person.say();
        System.out.println("在数据库中添加成功");
    }
}
applicationcontext-scan.xml为全局配置文件:

<?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.3.xsd">
   <context:component-scan base-package="com.spring.beans.scan"></context:component-scan>
    
</beans>
运行结果

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值