Spring--使用注解开发

使用注解进行自动装配

须知:
导入约束。context约束
配置注解的支持: context:annotation-config/
实体类代码请参考:Spring框架–IOC详解+代码简单实例


<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">

    <context:annotation-config/>
	<bean id="cat" class="autowireBean.pojo.Cat"/>
    <bean id="cat12" class="autowireBean.pojo.Cat"/>
    <bean id="cat22" class="autowireBean.pojo.Cat"/>
    <bean id="dog" class="autowireBean.pojo.Dog"/>
    <bean id="dog11" class="autowireBean.pojo.Dog"/>
    <bean id="dog33" class="autowireBean.pojo.Dog"/>
    <bean id="people" class="autowireBean.pojo.People"/>
beans>
@Data
@AllArgsConstructor
@NoArgsConstructor
public class People {
    private String name;
    @Autowired
    @Qualifier(value = "dog11")
    private Dog dog;
//    @Autowired
    @Resource(name = "cat22")
    private Cat cat;
}

如果自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,可以使用Qualifier(value=“XX”)去配置@Autowired的使用。【XX表示bean的id】

@Resource(name=" ") || @Resource

@Autowired与@Resource

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autowired 通过byType的方式实现,而且要求这个对象存在【常用】
  • @Resource默认通过byname的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错【常用】
  • 执行顺序不同:@Autowired 通过byType的方式实现;;@Resource默认通过byname的方式实现

使用注解开发

spring4之后,使用注解需要导入aop的包
需要导入context约束,增加对注解的支持,

1.bean
2.属性如何注入
3.衍生的注解
@Component邮寄个衍生注解,我们在web开发中,会按照mvc三层架构分层!
dao层【@Repository】
service层【@Service】
controller层【@Controller】
4.自动装配置

5.作用域
6.小结:
xml与注解:

  • xml更加万能,适用于任何场合,维护简单方便
  • 注解 不是自己类使用不了 维护相对复杂

xml用来管理bean;

  • 注解只负责完成属性的注入;
  • 我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持
  
    <context:component-scan base-package="oneIOC.pojo"/>
    <context:annotation-config/>

使用Java的方式配置Spring

我们现在要完成不适用Spring的xml配置了,
纯Java

@Data
@AllArgsConstructor
@NoArgsConstructor
//这个注解的意思就是说明 这个类 被Spring接管了
@Component
public class User {
    @Value("23456")
    private String name;

    public void show(){
        System.out.println("name:"+name);
    }
}

//这个注解的意思就是说明 这个类 被Spring接管了
@Configuration
public class ConfigD {
    //注册一个Bean 方法的名字就是这个Bean 和之前写标签形式是一样的
    @Bean
    public User getUser(){
        return new User();
    }
}

public class ConfigTest {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(ConfigD.class);
        User getUser = context.getBean("getUser",User.class);
        System.out.println(getUser.getName());
    }
}

你可能感兴趣的:(Java,spring,java,spring,boot)