Spring 上篇

一、Spring理念:

  1、使现有的技术更加容易使用 ,本身是一个大杂烩,整合了现有的技术框架

  2、之前的SSH:Struct2+Spring+Hibernate

  3、现在的SSM:Springmvc+Spring+Mybatis

  4、官网:https://docs.spring.io/spring-framework/docs/current/avadoc-api/

二、Spring优点:

  1、Spring是一个开源的免费的框架(容器)

  2、Spring是一个轻量级的,非入侵的框架

  3、控制反转(ioc),面向切面 编程(aop)

  4、支持事务的处理,对框架整合的支持

总结:Spring就是一个轻量级的控制反转(ioc)和面向切面编程(aop)的框架!

三、Spring组成:

  1、七大模块

      

 

   拓展:1、Spring boot 

          前题:需要掌握Spring和Springmvc

           一个快速开发的脚手架

           基于SpringBoot可以快速的开发单个微服务’

          约定大于配置

     2、Spring Cloud

          SpringCloud是语句Spring Boot实现的

四、IOC理论

    1、按照之前的习惯来写,

      第一步写UserDao接口

public interface UserDao {
    void getUser();
}

      第二写UserDaoImpl实现类

package com.zy.dao;

public class UserDaoImpl implements UserDao{

    @Override
    public void getUser() {
        System.out.println("你好! spring ioc");
    }
}

      第三步写UserService接口

package com.zy.service;

public interface UserService {
    void getUser();
}

      第四步写UserServiceImpl实现类

package com.zy.service;

import com.zy.dao.UserDao;
import com.zy.dao.UserDaoImpl;
import com.zy.dao.UserDaoMysqlImpl;

public class UserServiceImpl implements UserService{
    //调用userDaoImpl
    private UserDao userDao=new UserDaoImpl();

    @Override
    public void getUser() {
        userDao.getUser();

    }
}

      最后,测试

import com.zy.dao.UserDaoMysqlImpl;
import com.zy.service.UserServiceImpl;

public class MyTest {
    public static void main(String[] args) {
        //用户实际调用的是业务层 ,到曾它们不需要接触
        UserServiceImpl userService = new UserServiceImpl();
      
        userService.getUser();
    }
}

   如果我再创建一个UserDaoImp的实现类,里面的内容不一样,同在想要实现,我们又再UserServicelmp再来new一个UserDaolmp对象,最后测试

package com.zy.dao;

public class UserDaoMysqlImpl implements UserDao{
    @Override
    public void getUser() {
        System.out.println("你好! mysql");
    }
}
package com.zy.service;

import com.zy.dao.UserDao;
import com.zy.dao.UserDaoImpl;
import com.zy.dao.UserDaoMysqlImpl;

public class UserServiceImpl implements UserService{
    //调用userDaoImpl
   /* private UserDao userDao=new UserDaoImpl();*/

    //调用userDaoMysqlimpl
    private UserDao userDao=new UserDaoMysqlImpl();
  
   
    @Override
    public void getUser() {
        userDao.getUser();

    }
}

    代码量少还可以接受,如果代码量大的话,则会提高代码的耦合性,跟程序员来了很大工作量。

    因此 我们在UserServiceImpl使用一个Set接口,测试

package com.zy.service;

import com.zy.dao.UserDao;
import com.zy.dao.UserDaoImpl;
import com.zy.dao.UserDaoMysqlImpl;

public class UserServiceImpl implements UserService{
    //调用userDaoImpl
   /* private UserDao userDao=new UserDaoImpl();*/

    //调用userDaoMysqlimpl
   /* private UserDao userDao=new UserDaoMysqlImpl();*/

       private UserDao userDao;

    //利用set进行动态实现的注入
    public void setUserDao(UserDao userDao){
        this.userDao=userDao;
    }
    @Override
    public void getUser() {
        userDao.getUser();

    }
}
import com.zy.dao.UserDaoMysqlImpl;
import com.zy.service.UserServiceImpl;

public class MyTest {
    public static void main(String[] args) {
        //用户实际调用的是业务层 ,到曾它们不需要接触
        UserServiceImpl userService = new UserServiceImpl();
        ((UserServiceImpl) userService).setUserDao(new UserDaoMysqlImpl());
        userService.getUser();
    }
}

  总结:之前我们用原来的方式,是程序在主动的创建对象,使用set注入后,程序不再再去管理对象的创建,系统的耦合性大大降低,可以更加专注的再业务的实现,这就是IOC的原型。

  2、IOC的本质

  a、IOC(控制反转)是一种设计思想,DI(依赖注入)是实现IOC的一种实现方式。

  b、IOC是spring框架的核心内容,使用多种方式完美的实现了IOC,可以使用XML配置,也可以使用注解   

  c、控制反转是一种通过描述(xml或者注解)并通过第三方去生产或获取特定的对象。在spring中实现控制反转是IOC控 制,其实现方法是依赖注入(DI)

   拓展:采用xml方法配置Bean的时候,Bean的定义信息是和实现分离的,     

    采用注解的方式,可以把定义信息和实现合并:

一个案例:

创建一个实体类:

package com.zy.pojo;
​
public class Hello {
    private String str;
​
    public String getStr() {
        return str;
    }
​
    public void setStr(String str) {
        this.str = str;
    }
​
    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

创建一个bean.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
                        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--使用spring来创建对象,在spring这些都成为bean
    类型  变量名=new 类型();
     bean=对象     new Hello();
     Hello hello =new Hello();
​
     id  =变量名
     class=new 的对象
     property  相当于给对象中的属性设置一个值
    
    ref  :引用spring容器中创建好的对象
    value :具体的值,基本的数据类型
​
   -->
    <bean id="hello" class="com.zy.pojo.Hello">
        <property name="str" value="Spring"/></bean>
</beans>

测试:

import com.zy.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
​
public class MyTest {
    public static void main(String[] args) {
        //获取Spring的上下文对象
        //(解析beans.xml文件,生成管理相应的bean对象)
        ApplicationContext  context = new ClassPathXmlApplicationContext("beans.xml");
        //把对象现在都有spring中管理,要使用的话,直接去里面取出来就可以了
        //getBean:参数即为spring配置文件中的bean的id
        Hello hello =(Hello) context.getBean("hello");
        System.out.println(hello.toString());
​
    }
}

  思考:hello对象是由谁创建的?

        hello对象是由Spring创建的

      hello对象的属性是怎么设置的?

          hello对象的属性是由spring容器设置的

    这个过程就叫控制反转

    控制:谁来控制对象的创建,传统应用的程序的对象是由程序本身来控制管理的,使用spring后,对象是有spring来创建的

    反转:程序本身不创建对象,而变成被动的接受对象

    依赖注入:就是利用set方法来进行注入的

    结论:所以,我们不会在去程序中去修改,如果我们要实现不同的操作,只需去xml配置中进行修改,

    因此,所谓的IOC ,一句话搞定:对象由Spring来创建,管理,装配

  3、IOC创建对象的方式

    a、使用无参构造对象,默认
package com.zy.pojo;
​
public class User {
    public void User(){
        System.out.println("user的无参构造");
    }
    private String name;
​
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
    public void show(){
        System.out.println("name:"+name);
    }
}

 

<?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
                        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="user" class="com.zy.pojo.User">
        <property name="name" value="年华"/>
    </bean>
</beans>

测试

import com.zy.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
​
public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
       User user = (User) context.getBean("user");
       user.User();
        user.show();
    }
}
  b、使用有参构造
package com.zy.pojo;
​
public class User {
    private String name;
​
    public void User(){
        System.out.println("user的无参构造");
    }
    public User(String name){
       this.name=name;
    }
​
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
    public void show(){
        System.out.println("name:"+name);
    }
}

  有参构造又分为三种:下标赋值,类型创建,参数名设置

<!--第一种,下标赋值-->
<bean id="user" class="com.zy.pojo.User">
     <constructor-arg index="0" value="年华"/>
 </bean><!--第二种:通过类型创建    不建议使用-->
 <bean id="user" class="com.zy.pojo.User">
     <constructor-arg type="java.lang.String" value="zhaoyu"/>
 </bean><!--第三种:直接通过参数名来设置-->
 <bean id="user" class="com.zy.pojo.User">
     <constructor-arg name="name" value="年华"/>
 </bean>

    总结:在配置文件加载中,容器中管理的对象就已经初始化了

  4、Spring的配置

      a、别名
<!--别名  :如果添加了别名,我们也可以使用别名获取到这个对象-->
<alias name="user" alias="UserName"/>
    b、Bean的配置
<!--id :bean的唯一标识符,也相当于我们学的对象名
        class :bean 对象所对应的全限定名 :表名+类型
        name :也是别名,而且name更高级,可以同时取多个别名  -->
    <bean id="user" class="com.zy.pojo.User" name="user3 user5,user6;user7">
        <constructor-arg name="name" value="年华"/></bean>
    c、import

    import ,一般用团队开发使用,他可以将多个配置文件,导入合并为一个

<?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
                        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <import resource="beans.xml"/>
    <import resource="beans1.xml"/>
    <import resource="beans2.xml"/>
    <import resource="beans3.xml"/>
</beans>

  测试

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
       User user = (User) context.getBean("user5");
​
        user.show();
    }
}

  5、依赖注入(DI)

    a、构造器注入

      参考3的内容

    b、set方法注入(重点)

      依赖注入:set注入

      依赖:bean对象的创建依赖于spring容器

      注入:bean对象中的所有属性,由spring容器来注入

package com.zy.pojo;
​
import java.util.*;
​
public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> card;
    private Set<String> games;
    private String wife;
    private Properties info;
​
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
​
    public Address getAddress() {
        return address;
    }
​
    public void setAddress(Address address) {
        this.address = address;
    }
​
    public String[] getBooks() {
        return books;
    }
​
    public void setBooks(String[] books) {
        this.books = books;
    }
​
    public List<String> getHobbys() {
        return hobbys;
    }
​
    public void setHobbys(List<String> hobbys) {
        this.hobbys = hobbys;
    }
​
    public Map<String, String> getCard() {
        return card;
    }
​
    public void setCard(Map<String, String> card) {
        this.card = card;
    }
​
    public Set<String> getGames() {
        return games;
    }
​
    public void setGames(Set<String> games) {
        this.games = games;
    }
​
    public String getWife() {
        return wife;
    }
​
    public void setWife(String wife) {
        this.wife = wife;
    }
​
    public Properties getInfo() {
        return info;
    }
​
    public void setInfo(Properties info) {
        this.info = info;
    }
​
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", address=" + address.toString() +
                ", books=" + Arrays.toString(books) +
                ", hobbys=" + hobbys +
                ", card=" + card +
                ", games=" + games +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }
}

 

package com.zy.pojo;
​
public class Address {
    private String Address;
​
    public String getAddress() {
        return Address;
    }
​
    public void setAddress(String address) {
        Address = address;
    }
​
    @Override
    public String toString() {
        return "Address{" +
                "Address='" + Address + '\'' +
                '}';
    }
}

 

<?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
                        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="address" class="com.zy.pojo.Address"/>
    <bean id="student" class="com.zy.pojo.Student">
        <!--第一种,普通值注入,用value -->
        <property name="name" value="赵娱"/>
        <!--第二种,bean注入-->
        <property name="address" ref="address"/>
        <!--第三种,数组注入-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>三国演义</value>
                <value>水浒传</value>
            </array>
        </property>
        <!--第四种,list注入-->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>追剧</value>
                <value>唱歌</value>
                <value>跳舞</value>
            </list>
        </property><!--第五种,map注入-->
        <property name="card">
            <map>
                <entry key="身份证" value="145289635258794"/>
                <entry key="学号" value="174006021078"/>
            </map>
        </property>
        <!--第六种,set注入-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>coc</value>
                <value>bob</value></set>
        </property>
        <!--第七种,null值注入-->
        <property name="wife">
            <null></null>
        </property>
        <!--第八种,properties注入-->
        <property name="info">
            <props>
                <prop key="学号">174006021078</prop>
                <prop key="姓名">小花</prop>
                <prop key="性别"></prop>
            </props>
        </property>
    </bean>
​
​
​
</beans>

  测试

import com.zy.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
​
public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.toString());
    }
}
 
  c、其他方式注入(拓展方式注入)

    可以使用p命令空间和c命名空间进行注入

<?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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd"><!--p 命令空间注入  可以直接注入属性的值  :property-->
    <bean id="user" class="com.zy.pojo.User" p:name="赵娱" p:age="22"/>
    <!--c 命令空间注入  通过构造器注入:construct-args-->
    <bean id="user2" class="com.zy.pojo.User" c:age="22" c:name="zhaoyu"/>
​
​
</beans>

  测试

@Test
public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
    User user = context.getBean("user", User.class);
    System.out.println(user);
}
​
@Test
public void test1(){
    ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
    User user = context.getBean("user2", User.class);
    System.out.println(user);
}

    注意点:

      p命名和c命名空间不能直接使用,需要导入

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"

  6、bean的作用域

         a、singleton(单例模式,spring默认的机制)

<bean id="user2" class="com.zy.pojo.User" c:age="22" c:name="zhaoyu" scope="singleton"/>

  b、prototype(原型模式)

      每一次从容器中get的时候,都会产生一个新的对象

<bean id="user2" class="com.zy.pojo.User" c:age="22" c:name="zhaoyu" scope="prototype"/>

  c、request、session、application,这些只能在web开发中使用到

    7、Bean的自动装配

    自动装配式spring满足bean依赖的一种方式,spring会在上下文种自动寻找,并自动给备案装配属性

     在spring中有三种装配方式

        1、在xml中显示的配置

        2、在java中显示配置

        3、隐式的自动装配bean(重要的)

    例子:

      假设一个人有两个宠物

      1、(手动装配)
package com.zy.pojo;
​
public class Cat {
    public void shout(){
        System.out.println("喵");
    }
}
package com.zy.pojo;
​
public class Dog {
    public void shout(){
        System.out.println("旺");
    }
}

 

package com.zy.pojo;
​
public class People {
    private Cat cat;
    private Dog dog;
    private String name;
​
    public Cat getCat() {
        return cat;
    }
​
    public void setCat(Cat cat) {
        this.cat = cat;
    }
​
    public Dog getDog() {
        return dog;
    }
​
    public void setDog(Dog dog) {
        this.dog = dog;
    }
​
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
​
    @Override
    public String toString() {
        return "People{" +
                "cat=" + cat +
                ", dog=" + dog +
                ", name='" + name + '\'' +
                '}';
    }
}

 

<?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
                        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="cat" class="com.zy.pojo.Cat"/>
    <bean id="dog" class="com.zy.pojo.Dog"/>
    <bean id="people" class="com.zy.pojo.People">
        <property name="name" value="zhaoyu"/>
        <property name="cat" ref="cat"/>
        <property name="dog" ref="dog"/>
    </bean>
​
​
</beans>

  测试

@Test
public void Test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    People people = context.getBean("people", People.class);
    people.getCat().shout();
    people.getDog().shout();
}
  2、byname、bytype自动装配
<!--byName :会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean id
    bytype :会自动在容器上下文中查找,和自己对象属性类型相同的bean id --><bean id="people" class="com.zy.pojo.People" autowire="byName">
<bean id="people" class="com.zy.pojo.People" autowire="byType">

  总结:

    byname的时候,需要保证所有bean的id唯一性,并且这个bean需要和自动注入的属性的set方法的值一致

    bytype的时候,需要保证所有的bean的class唯一,并且这个bean需要和自动注入的属性的类型一致

  3、注解自动装配

      jdk1.5支持的注解,Spring2.5就支持注解了。

      要使用注解须知:

      1、导入约束 context约束

      2、配置注解的支持 context:annotation-config

`<?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
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/> </beans>`
      3、自动装配的注解:@Autowired 、@Qualifier、@Resource、@Nullable 、@Component

    @Autowired

        直接在属性上使用,也可以在set方式上使用

        使用Autowired时,我们可以不用编写set方法,但前提是这个自动装配的属性在IOC容器中

package com.zy.pojo;
​
import org.springframework.beans.factory.annotation.Autowired;
​
public class People {
    @Autowired
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;
​
    public Cat getCat() {
        return cat;
    }
    public Dog getDog() {
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    public String getName() {
        return name;
    }
    @Override
    public String toString() {
        return "People{" +
                "cat=" + cat +
                ", dog=" + dog +
                ", name='" + name + '\'' +
                '}';
    }
}

 

<?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/aop/spring-aop.xsd">
    <!--开启配置注解的支持-->
    <context:annotation-config/>
    <bean id="cat" class="com.zy.pojo.Cat"/>
    <bean id="dog" class="com.zy.pojo.Dog"/>
    <bean id="people" class="com.zy.pojo.People"/>
​
​
​
</beans>

 

  拓展:

    1、@Nullable 如果字段标记了这个注解的话,说明这个字段可以为null

public People(@Nullable  Cat cat) {
    this.cat = cat;
}

    2、@Autowired(required = false) 如果显示定义了autowired的required属性为false,说明这个对象可以为null,否则不允许 为空

    3、如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解 @Autowired 完成的时候,我们可以使用 @Qualifier(value = "新的名字")去配置@Autowired的使用,指定一个唯一的bean对象的注入

    4、@Resource(name="新名字")

    5、@Component :组件 ,放在类上,说明这个类被spring管理了,就是bean

    6、@Autowired和@Resource的区别:

        相同:都是用来自动装配的,都可以放在属性的字段上

        不相同:

          1、@Autowired:通过byname的方式实现 ,而且必须要求这个对象存在(常用)

            @Resource:默认通过byname的方式实现,如果找不到名字,则通过bytype实现,如果两个都找不到的情况下,就会报错!

          2、@Autowired:自动装配通过类型,名字,如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value = "新的名字")

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

          3、执行顺序不同:@Autowired通过byType的方式实现,@Resource:默认通过byname的方式实现

  8、使用注解开发

    在spring4之后,使用注解开发,必须要保证aop的包导入了

 使用 注解需要导入context约束,增加注解的支持

  a、bean
<?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
               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:component-scan base-package=" com.zy.pojo"/> <!--开启注解支持--> <context:annotation-config/> <bean id="user" class="com.zy.pojo.User"/> ​ ​ </beans>
package com.zy.pojo;
​
import org.springframework.stereotype.Component;
​
@Component   /*等价于 <bean id="user" class="com.zy.pojo.User">
               @Component 组件 */
public class User {
    public String name="赵";
}

 

测试

@Test
public void Test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    User user = context.getBean("user", User.class);
    System.out.println(user.name);
}
  b、属性注入
@Component   /*等价于 <bean id="user" class="com.zy.pojo.User">
               @Component 组件 */
public class User {
​
    public String name;
    
    /*相当于 <property name="name" value="zhaoyu"/>*/
    @Value("zhaoyu")
    public void setName(String name) {
        this.name = name;
    }
}
    c、衍生的注解

  @Component有几个衍生注解,在web开发中,会按照mvc三层架构分层

    dao层 -----[@Repository]

    service层 ----[@Service]

    controller层---[@Controller]

            这四个注解功能都是一样的,都是代表将某一个类注册到spring中,装配Bean
   d、自动装配配置

  @Autowired:自动装配通过类型,名字,如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value = "新的名字")

  @Nullable 如果字段标记了这个注解的话,说明这个字段可以为null

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

  e、作用域

    @Scope("singletor") 单例模式

  总结:

    xml与注解:

      xml更加万能,适用于任何场合,维护更加方便

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

    xml与注解最佳实践:

      xml用来管理bean

      注解只负责完成属性的注入

      在使用的过程中,只需要注意一个问题:必须要让注解生效,就需要开启注解的支持

<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.zy"/>
<!--开启注解支持-->
<context:annotation-config/>

 

  9、使用java的方式配置spring

  我们现在不要完全使用spring的xml配置了,全权交给java来做!

  javaConfig是spring的一个子项目,在spring4之后,它成为了一个核心功能!

  入门

  一个实体类

package com.zy.pojo;
​
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
​
/*这里的这个注解的意思是,这个类被spring接管了,被注册到了容器中*/
@Component
public class User {
    private String getName;
​
    public String getName() {
        return getName;
    }
    @Value("zhaoyu") //注入属性值
    public void setGetName(String getName) {
        this.getName = getName;
    }
​
    @Override
    public String toString() {
        return "User{" +
                "getName='" + getName + '\'' +
                '}';
    }
}

 

一个配置类(自定义)

package com.zy.config;
​
import com.zy.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
​
@Configuration  //也会被spring容器接管,也会被注册到容器中,因为它也是一个@Component
                //@Configuration  代表这是一个配置类,就和我们之前看的beans.xml
@ComponentScan("com.zy.pojo")
@Import(MyConfig1.class)  //把其他的配置类融合在一个配置类中
public class MyConfig {
​
    //注册一个bean ,就相当于我们之前写的一个bean标签
    //这个方法的名字,就相当于bean标签中的id属性
    //这个方法的返回值,就相当于bean标签中的class属性
    @Bean
    public User getUser(){
        return new User(); //就是返回到注入到bean的对象!
    }
​
}

  测试

import com.zy.config.MyConfig;
import com.zy.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
​
public class MyTest {
    public static void main(String[] args) {
        //如果我们完全使用配置类方式去做,我们就只能通过AnnotationConfig 上下文来获取容器
        //通过配置类的class对象加载!
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User user = (User) context.getBean("getUser");
        System.out.println(user.getName());
    }
​
}

      注:这样的纯java的配置方式,在springboot中都可以看见

posted @ 2021-03-30 16:53  年华只余一地悲凉  阅读(51)  评论(0编辑  收藏  举报
/*粒子线条,鼠标移动会以鼠标为中心吸附的特效*/