您的位置:首页 > 编程语言 > Java开发

自定义注解、Java启动spring

2016-12-07 00:00 393 查看
#1:自定义注解类

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.stereotype.Component;

@Target({ElementType.TYPE})   //这个是说明这个注解类用在哪里。
@Retention(RetentionPolicy.RUNTIME)  //这个注解类的生命周期,是整个jvm的运行周期。
@Component				//这个不是必须的,只是为了让spring可以扫描来创建它
public [@interface](https://my.oschina.net/u/996807) RpcServiceTest{
String value();    //这个用于传进一个信息,到时候可以获取出来。
//如果value是枚举类型,就需要写着这里,作为内部类
}

#2:用法

package org.liufu.prc;

@RpcServiceTest(value = "AnotactionA.class")
public class AnotactionA {

}

#3:不借助tomcat,直接使用spring框架的类:ClassPathXmlApplicationContext来启动spring框架

package org.liufu.prc;

import java.util.Iterator;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class StrartClass{

@SuppressWarnings("resource")
public static void main(String[] args) {

//这句话非常重要,他就是spring框架的入口,调用了它之后,spring.xml里面的bean都被实例化了。
ClassPathXmlApplicationContext cxt = new ClassPathXmlApplicationContext("spring.xml");

//根据注解类来获取用它注解的所有string(没什么用!)和类实例
Map<String, Object> mapBean = cxt.getBeansWithAnnotation(RpcServiceTest.class);
Iterator<Object> ite = mapBean.values().iterator();
while (ite.hasNext()) {
Object obj = ite.next();
//打印注解的时候传进去的“消息”
System.out.println(obj.getClass().getAnnotation(RpcServiceTest.class).value());
}
}
}

#总结:

spring框架可以在tomcat中启动

web.xml --> spring 类装载器 ---->spring.xml 就可以创建配置的类实例了。

spring框架也可以直接在Java项目中启动(最直接)

ClassPathXmlApplicationContext cxt = new ClassPathXmlApplicationContext("spring.xml");

所以说,spring框架,可以用于web项目,也可以用于Java项目。

对于代码的调试也没有影响,像平时一样调试就行了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息