spring常用注解解析
-
@Autowired: 自动装配通过类型(type),名字(name),如果Autowired不能唯一自动装配上属性,则需要通过@jQualifier(value="xxx")(别名)
1.1、@Autowired
<?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" xmlns:aop="http://www.springframework.org/schema/aop" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/context/spring-aop.xsd"> <context:annotation-config/> <bean id="cat" class="Cat"/> <bean id="dog" class="Dog"/> <bean id="people" class="People"/> </beans>
public class People { //required = false 表示Cat属性可以为空 @Autowired( required = false) private Cat cat; @Autowired //@Qualifier 当Dog属性有多个id名时,表示为Dog属性显示的指定id名,配合@Autowired使用 @Qualifier(value = "dog") private Dog dog; private String name;
-
@Resource : 自动装配,通过名字(name),类型(type)。
//name 表示指定bean的名字,如果不指定,那么就会按照先id,后类型的顺序扫描bean @Resource(name = "cat1") private Cat cat;
-
@Component (@Scope("singleton/prototype")) : 组件,放在类上,说明这个类被Spring管理了,就是bean;
import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; //@Component 等价于 <bean id="user" class="com.lix.pojo.User"/> @Component @Scope("prototype")//原型模式 public class User { public String name = "lix"; @Value("ll") public void setName(String name) { this.name = name; } }
-
@Component 有几个衍生的注解,我们在web开发中,会按照mvc三层架构分层
-
dao【@Repository】
-
service【@Service】
-
controller【@Controller】
-
上面四个注解功能时一样的,代表将某个类装配为bean
-
@Value("xxx") :相当于
<name="xxx" value="xxx"/>
@Value("ll")
public void setName(String name) {
this.name = name;
}
-
@Configration
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @ComponentScan("com.lix.pojo") @Import(LixConfig2.class) public class LixConfig { @Bean public User getUser() { return new User(); } }
本文来自博客园,作者:六爻呈乾,转载请注明原文链接:https://www.cnblogs.com/ilycq/p/13901220.html