Spring 入门 Ioc-Annotation

通过对XML版本进行修改:http://www.cnblogs.com/likailan/p/3446821.html

一、导入 Spring 所需要的包

spring-framework-2.5.6 版需要导入以下包:
和XML版一样。

spring-framework-3.2.4 版需要导入以下包:
和XML版一样。

其他版本没有作测试。

二、修改Spring配置文件

通过 Annotation 声明 bean 则不需要在配置文件中声明了,把配置文件修改为:

<?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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:component-scan base-package="com.spring" />
    
</beans>

1.添加context明名空间(代码4、7、8行)。

2.添加代码 <context:component-scan base-package="com.spring" /> 告诉Spring扫描 com.spring 包(包括子包)下的所有类而找到bean。

三、通过Annotation 声明bean

在类名上加上注解@component

@Component(“user”)
public class User {
    private int id;
    private String name;
    private Book book;
    //省略get set方法....

}

@Component后面参数为该bean 的id。

spring-framework-3.2.4 版可以通过在set方法前加上@Value注解为相应属性设置初值,如下:

@Value("张三")
public void setName(String name) {
   this.name = name;
}
原文地址:https://www.cnblogs.com/likailan/p/3456188.html