Spring框架bean的注解管理方法之一 使用注解生成对象

Spring框架bean的注解管理方法之一 使用注解生成对象

首先在原有的jar包:

需Spring压缩包中的四个核心JAR包

beans 、context、core 和expression

下载地址:

https://pan.baidu.com/s/1qXLHzAW

以及日志jar包

commons-logging 和log4j

下载地址:

https://pan.baidu.com/s/1mimTW5i

再增加一个

spring-aop-5.0.1.RELEASE.jar

增加注解功能的jar包名字是aop有些奇怪(不是annotation ,也不是context)


然后,src中建立一个xml配置文件,增加新的context的约束语句,如下:

<?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"> 
      <!--  开启注解扫描  -->
     <context:component-scan base-package="com.swift"></context:component-scan>
</beans>

注解的方法xml中配置对象及属性只用这一句

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

即可,com.swift是包名,最好写上一级,可以扫描到里边所有的包

下边使用注解来创建对象:

package com.swift.user;

import org.springframework.stereotype.Component;

@Component(value="user")
public class User {
    public String fun() {
        return "The User's fun()..........";
    }
}
 

注解创建对象

@Component(value="user")

或者

@Component

默认就是生成user对象

相当于之前在xml配置文件中使用<bean ></bean>

实际上除了可以用@Component 还可以用@Service @Controller @Repository ,功效一样,分别预备service层 web层 dao层使用的

默认单例,如果要多例可以这样写

@Component(value="user")

@Scope(value="prototype")

关于value="prototype" 还有待补充


 struts2的Action使用多例 有成员变量的用多例 否则会引起多线程的并发