在spring中,有关bean的设置不仅可以通过xml来实现,还可以用注解直接在代码中实现
第一步:配置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"
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.imooc.beanannotation"></context:component-scan>
</beans>
中间类
package com.imooc.beanannotation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Scope("prototype")
@Component("bean")
public class BeanAnnotation {
public void say(String arg)
{
System.out.println(arg);
}
}
测试类
package com.imooc.beanannotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestBeanAnnotation {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-beanannotation.xml");
BeanAnnotation bean=ctx.getBean("bean",BeanAnnotation.class);
BeanAnnotation bean2=ctx.getBean("bean",BeanAnnotation.class);
bean.say("this is a test");
System.out.println(bean.hashCode());
System.out.println(bean2.hashCode());
}
}
可以看见,我们并未配置xml,这是单单用注解就实现的bean的配置。
常见的定义bean的注解有:Component(通用)Repository(持久层)Service(服务层)Controller(控制层)
我们通过Scope注解定义bean的作用域,prototype与singgleton多例与单例