java Spring 基于注解的配置(一)

本文展示了如何在Spring框架中配置注解处理器,并通过组件扫描自动注册类。包括了UserService类的定义与初始化,以及如何从XML配置文件中注入并使用此类。

注解引用:1.service.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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">


<!--将针对注解的处理器配置好  -->     
<context:annotation-config /> 
 
<context:component-scan base-package="*.*"/> 
</beans>

2.UserService.java

使用@Service 命名该类的name

使用@Controller("userService") 效果也是一样

如果单使用@Controller 那么命名就只能用userService 这样的驼峰

package com.sun.service;

import java.util.ArrayList;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("userservice")
public class UserService {
    private String name;
    private ArrayList arr;
        public ArrayList getArr() {
        return arr;
    }
    public void setArr(ArrayList arr) {
        this.arr = arr;
    }
    public UserService(){
        System.out.println("this is chushihua");
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void init(){
        System.out.println("init------------");
    }
    public void cleanup(){
            System.out.println("cleanup------------");
    }
        
}
    

3.HelloWorld.java

package com.sun.service;

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

public class HelloWorld {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        AbstractApplicationContext app = new ClassPathXmlApplicationContext("service.xml");
        UserService us  = (UserService) app.getBean("userservice");
        us.setName("Hello World");
        System.out.println(us.getName());
        //us.setName("sunzhiyan");
        /*System.out.println(us.getName());
        for(int i = 0;i < us.getArr().size();i++){
            System.out.println(us.getArr().get(i));
        }
        app.registerShutdownHook();*/
        
    }

}

这样能够进行输出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值