条件
导入依赖包(需要保证springframework:spring-aop包的导入)
添加context约束
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
<context:annotation-config/>
@Component
<!--指定扫描的包,该包下的注解生效-->
<context:component-scan base-package="java"/>
base-package 指明使用范围是哪个包
@Component //等价于<bean id ="test" class= "Test"/> id默认为类名的小写
public class Test{
public String name;
}
@Value()可以放在属性或set方法,()内为赋值
@Component //等价于<bean id ="test" class= "Test"/> id默认为类名的小写
public class Test{
@Value("xxxxx")//等价于 <property name="name" value="xxxx"/>
public String name;
}
@Scope 作用域
@Component //等价于<bean id ="test" class= "Test"/> id默认为类名的小写
@Scope("singleton") //等价于于<bean id ="test" class= "Test" scope="singleton"/>
public class Test{
@Value("xxxxx")//等价于 <property name="name" value="xxxx"/>
public String name;
}
衍生注解
mvc模式
dao【@Repository】
service【@Service】
controller【@Controller】
功能同Component一样
@Configuration(使用java的方式配置Spring)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component//说明Configuration也是一个组件
public @interface Configuration {
boolean proxyBeanMethods() default true;
}
将一个类定义为配置类,等同于xml文件
在配置类中用@Bean标记对应的bean类,方法名即为bean-id
@Configuration //本身也是一个组件
@ComponentScan("")//因此也可以配置扫描的包
public class Config {
@Bean //等价于注册一个bean id为方法名,class为返回值的类型
public User getUser(){
return new User();
}
}
public class Mytest {
public static void main(String[] args) {
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext();
User u=context.getBean("getUSer",User.class);
System.out.println(u.getName());
}
}