依赖注入
不同数据类型的注入方式
public class Student { private String name; private Address address; private String[] stationeries; private Listhobbies; private Mapbook; private Setgames; private String wife; private Properties info; ...
rulereraserpencilLOLCODCSsingdancerapbasketballzhangsan12345678
除了通过 setter 注入、构造器注入还可以通过类似的 p-namespace
和 c-namespace
进行注入,具体参看官方文档的例子,使用命名空间注入
Bean 作用域
Scope | Description |
---|---|
singleton | (Default) Scopes a single bean definition to a single object instance for each Spring IoC container. |
prototype | Scopes a single bean definition to any number of object instances. |
request | Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext . |
session | Scopes a single bean definition to the lifecycle of an HTTP Session . Only valid in the context of a web-aware Spring ApplicationContext . |
application | Scopes a single bean definition to the lifecycle of a ServletContext . Only valid in the context of a web-aware Spring ApplicationContext . |
websocket | Scopes a single bean definition to the lifecycle of a WebSocket . Only valid in the context of a web-aware Spring ApplicationContext . |
Bean 的自动装配
Spring 中有三种装配方式
xml 中显式的配置
public class People { private String name; private Animal cat; private Animal Dog; ... public class Cat implements Animal { @Override public void bark() { System.out.println("miao~"); } } public class Dog implements Animal { @Override public void bark() { System.out.println("wang~"); } }
隐式的自动装配 bean
setAbc()
对应的 bean id 就应该为 abc
通过类型自动装配,需要参数为不同的类型才能使用,不然会报错 NoUniqueBeanDefinitionException
也就是当前示例中的 cat
和 dog
不能再使用 Animal
声明,应改为
private Cat cat;
private Dog dog;
使用注解实现自动装配 Bean
修改配置支持注解的方式
代码中只需要加上 @Autowired
即可实现自动装配 bean
正确使用该方式的情况下可以不声明 setter 也能自动装配,与上面的 xml 不同
装配的方式为先按类型,再按名字
如果
cat
声明为 Cat 类型,即cat
和dog
为不同类型的时候,那么 bean id 和属性不用同名(setter 可有可无所以也不用同名),类似于 xml 中的autowire="byType"
如果
cat
和dog
为相同类型的时候,如代码中都声明为Animal
类型,那么会通过名字去匹配,需要bean id 和属性名字相同,相当于 xml 中的autowire="byName"
public class People { private String name; @Autowired private Animal cat; @Autowired private Animal dog; ...
如果存在多个 bean 想装配其中指定的某个的时候,可以使用 @Qualifier
注解实现
public class People { private String name; @Autowired private Animal cat; @Autowired @Qualifier("dog2") //指定使用 dog2 private Animal dog; ...
也可以使用 @Resource
注解实现上述功能,功能和 @Autowired
相同,不过可以直接指定 bean id
import javax.annotation.Resource; public class People { private String name; //@Autowired @Resource private Animal cat; //@Autowired //@Qualifier("dog2") @Resource private Animal dog; ...
Copyright © 2004-2024 Ynicp.com 版权所有 法律顾问:建纬(昆明)律师事务所 昆明市网翼通科技有限公司 滇ICP备08002592号-4