码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-04-19 17:12:16      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:

注解引用: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();*/
        
    }

}

这样能够进行输出。

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

标签:

原文地址:http://www.cnblogs.com/sunxun/p/5408498.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!