注解方式开发, 使用 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
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:annotation-config/>
</beans>
注意:仅仅引用bean上注释
声明,使用spring5.0.7版本,JDK8,spring中的注解如下:
1、@Component 注解
【component代表成分组件的意思】 是把bean交给spring管理;
value:指定bean的id。如果不指定value属性,默认bean的id是当前类的类名。首字母小写
@Controller:一般用于表现层的注解。 web层
@Service:一般用于业务层的注解。 service层
@Repository:一般用于持久层的注解。 dao层
2、用于注入数据的 有 @Qualifier @Autowired @Resource @value
1、 @Qualifier
(1)它在给字段注入时不能独立使用,必须和@Autowire一起使用;但是给方法参数注入时,可以独立使用。
(2)还能够 指定id 注入;
2、@Autowired
用于自动注入bean 找到了就可以注入,找不到报错【使用该注解省略了setter 方法】
3、@Resource =@Autowired + @Qualifier
用于注入其他类型,
直接通过id 进行注入;
4、@value
用于注入基本数据类型和String类型,,可以通过${}在资源文件中取值【前提:外部文件被加载】
3、@Scope指定bean范围
value 指定范围的值;例如 @Scope( “ prototype ”)
取值:singleton prototype request session globalsession
4、批量扫包
5、生命周期相关的注解
@PostConstruct 加在方法上 初始化init
@PreDestory 加在方法上 销毁 destroy
注意:要看到@PreDestory的效果,需要调用ClassPathXmlApplicationContext.close方法,同时scope的值要是singleton。显示关闭ioc容器
常见的注解:
@Required ,@Autowired ,
该 @Required
注释适用于bean属性setter方法;
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Required
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// ...
}
将 @Autowired
注释应用于构造函数,也可用于 setter 方法,也可以用于成员变量和构造结合使用,也可以用于数组和集合:
spring4.3版本以后,若bean中仅仅定义了一个 构造,不需要注解;若存在多个构造,需要至少一个注解【用以告诉spring ioC 使用哪一个构造函数】;
public class MovieRecommender {
private final CustomerPreferenceDao customerPreferenceDao;
@Autowired
private MovieCatalog movieCatalog;
@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}
// ...
}
用于集合:
public class MovieRecommender {
private Set<MovieCatalog> movieCatalogs;
@Autowired
public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) {
this.movieCatalogs = movieCatalogs;
}
// ...
}
从Spring Framework 5.0开始,您还可以使用@Nullable
注释;
public class SimpleMovieLister {
@Autowired
public void setMovieFinder(@Nullable MovieFinder movieFinder) {
...
}
}