spring使用注解开发

在spring4之后,想要使用注解形式,必须引入aop的包

在配置文件中,还要引入一个context约束

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         https://www.springframework.org/schema/context/spring-context.xsd">

</beans>

1、配置扫描哪些包下的注解

<context:component-scan base-package="com.lili.entity"/>

2、开启对注解的支持

<context:annotation-config/>

Bean的实现:(@Component注解)

@Component
public class Address {
    private String address;
	// get,set,toString
}
@Component("student")
public class Student {
    private String name;
    private Address address;
	// get,set,toString
}

属性注入:(也可以在set方法上)

@Component
public class Address {
    @Value("china")
    private String address;
	// get,set,toString
}

衍生注解

@Component:三个衍生注解

为了更好的进行分层,Spring可以使用其它三个注解,功能一样,目前使用哪一个功能都一样。

  • @Controller:web层

  • @Service:service层

  • @Repository:dao层

写上这些注解,就相当于将这个类交给Spring管理装配了!

自动装配注解(@Autowired):

@Component("student")
public class Student {
    @Value("qijingjing")
    private String name;
    @Autowired
    private Address address;
	// get,set,toString
}

作用域

@scope

  • singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁。

  • prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收

@Component
@Scope("prototype")
public class Address {
    private String address;
	// get,set,toString
}
posted @ 2021-08-15 13:31  JamieChyi  阅读(17)  评论(0)    收藏  举报  来源