spring注解
使用注解之前:
1、若使用注解,需要在创建XML文件时,引入context名称的约束。
2、在创建的XML文件中,加上需扫描注解的包。如com.lijie,扫描后,spring容器才会有相应的对象创建。
<context:component-scan base-package="com.lijie"></context:component-scan>
回顾XML中对bean的配置
<bean name="" class="" scope="" init-method="" destory-method="">
<property name="" value=""|ref="">
(<list>
<value></value>
</list>
)
</property>
</bean>
使用注解:
1、用于创建对象的
出现位置:bean的最开头
相当于bean标签的
-
@Component:用于把当前对象存入spring容器
-
@Controller:与Component功能一样,是对三层架构表现层的区分
-
@Service:与component功能一样,是对三层架构业务层的区分
-
@Repository:与component功能一样,是对三层架构持久层的区分
取用时,若无备注id,则默认bean的名称,但首字母小写
例子:
@Component public class helloSpringImpl implements IhelloSpring {}
2、用于注入数据的
出现位置:在需要注入的变量或方法上。
相当于<property name="" value=""|ref="" >
-
@autowrite:在需要注入的数据前添加该注解,spring自动匹配容器中的values的类型并注入。若存在多个匹配值。则匹配容器中的ID值。
-
@Qualifier:在@autowrite下方指定名称进行注入,无法单独使用。属性:value:用于指定注入Bean的ID
@Autowired @Qualifier(value = "helloImpl1")//在@autowrite下方使用@qualifier指定注入对象 Ihello helloImpl=null;
-
@Resource:直接按照Bean的id注入,可以单独使用。 属性:name,用于指定注入bean的ID
@Resource(name = "helloImpl1") Ihello helloImpl=null;
上述三个注入注解(@autowrite @Qualifier @Resource)都只能注入bean类型的,无法注入String和基本类型数据,而复杂类型数据,如数组,map只能由XML文件注入
- @value:用于注入基本类型和String类型,属性:value
3、用于设置作用范围的
相当于scope
- @scope:用于指定bean的作用范围 属性:value,常用取值singleto(单例)\prototype(多例):默认单例
@Component
@Scope("prototype")
public class helloSpringImpl implements IhelloSpring {
@Resource(name = "helloImpl1")
4、和生命周期相关的
相当于init-method="" destory-method=""
public class Blue {
public Blue(){
System.out.println("Blue constructor ......");
}
public void init(){
System.out.println("init ing.....");
}
public void destroy(){
System.out.println("destroy");
}
}
public class MyConfing {
@Bean(initMethod = "init",destroyMethod = "destroy")
public Blue blue(){
return new Blue();
}
}
新注解
若想完全抛弃spring 配置xml,则需要创建一个配置类。
使用配置类后,获取核心容器就不能使用classPathXmlApplicationContext构造方法:
ApplicationContext ac= new ClassPathXmlApplicationContext(“bean.xml”);
而是改为AnnocationConfigApplicationContext构造方法:
ApplicationContext ac=new AnnocationConfigApplicationContext(“springConfig.class”)
- @Configuration
作用:指定当前类是一个配置类。
- @Componentscan
作用:用于通过注解指定spring在创建容器时扫描的jar包
参数:value或basePackages的作用一样,都是用与指定创建容器时要扫描的
@Configuration
@ComponentScan(value = "com.lijie")
public class Springconfig {
- @Bean
(name="")不写name则默认为方法名
作用:用于将当前方法返回值作为Bean对象存入容器中,key是name,value是返回的Bean。
当使用注解配置方法时,如@Bean。若改方法有参数,则spring自动在容器中查找有无符合的类型参数查找方式和@autowrite一样。先按类型匹配,若存在多个则按id匹配
- @import
(bean.class) 该注解是添加在一个主配置类中,当工程设置多个配置类时,在其中一个配置类中添加该注解,并添加 其他配置类.class 。获取容器时是要添加一个主配置类即可。
-
@PropertySource
作用:用于获取property的路径
参数:value,指定文件的名称和路径
关键字:classpath 表示类路径下。若不加,也是默认的类路径下。
对照注解形式:
<context:property-placeholder location="classpath:jdbc.properties"/>