Spring--->固定套路及注解说明

1、新建项目导包

 <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

2、新建beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="..." class="...">  
        <!-- collaborators and configuration for this bean go here -->
    </bean>
  //id就是对应的创建对象的名字,class是对应的类
    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>

 测试

@org.junit.Test
    public  void Test01() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = context.getBean("user", User.class);
        System.out.println(user.name);
    }

3、注解说明

自动装配

-@Autowired(    @Nullable   =false 允许字段为null)自动装配通过类型,名字

-@Qualifier(value="dog22") 指定bean为唯一值,配合@Autowired

-@Resource  自动装配通过类型名字

四个功能都一样,都是代表将某个类注册到Spring,装配Bean

-@Component  组件放在类上,说明被托管了,就是bean

-@Repository  【dao】

-@Service   【server】

-@Controller  【controller】

//  @Component组件等价于<bean name="user" class="com.xian.dao.User"/>
@Component
public class User {
    public String name="hanhanhan";
}

-@Value  放在set方法上效果一样

  // @Value等价于<property name="name" value="hanh"/>
    @Value("hanhanhan")
    public String name;

作用域

-@Scope("singleton")  作用域(单例模式)

 

xml与注解

  • xml更万能,适用于任何场景,维护更方便

  • 注解不是自己的类使用不了,维护相对复杂

最佳状态:

xml只管理Bean

注解完成值的注入

 

注意

必须让注解生效,就必须开启注解的支持

    <context:component-scan base-package="com.xian"/>
    <context:annotation-config/>

4、使用Java配置Spring

JavaConfig

 

posted @ 2020-09-11 12:29  Spring_Xian  阅读(164)  评论(0)    收藏  举报