Spring入门(三)——注解配置

除了使用xml文件配置外,从spring 3.0开始还提供了使用注解进行配置。
使用注解进行配置,可以简化繁琐的xml配置,将上例的HelloWorld修改为注解配置。

首先我们看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.xsd" >
     <!--该标签作用为扫描并自动为添加了相应注释的类注册Bean-->  
    <context:component-scan base-package="com.example.assembly"></context:component-scan>
   
</beans>

可以看到,现在的xml文件已经没有手动配置的Bean了,除了Spring的配置文件头部,只有一个context:component-scan标签,该标签表示IoC容器自动检测包下的类,并为添加了对应注释的Bean进行注册。

类文件变为:

package com.example.assembly;

import org.springframework.stereotype.Component;

@Component("hello")
public class assemblytest {
	
	private String name;
	
	public assemblytest(String name) {
		this.name = name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public void say() {
		System.out.println(name+" say:"+"Hello World"+this.hashCode());
	}
	
}

仅仅是在类上添加了一个注解@Component,相当于告诉IoC容器扫描到时需要为这个类注册Bean。
运行结果和之前相同。

这样就大大简化了Bean的配置,常用的注解还有很多,在此仅以一个简单的例子抛砖引玉。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值