Autowired用法

708 阅读1分钟

推荐文档:Spring @Autowired 注解_w3cschool

用法案例

一、接口,在接口中实现了一个save方法

package com.example.autowired;

public interface UserRepository {

    void save();
}

复制

二、实现接口,重写接口中的方法

package com.example.autowired;

import org.springframework.stereotype.Repository;

@Repository("userRepository")
public class UserRepositoryImps implements UserRepository{

    @Override
    public void save() {
        System.out.println("爱吃棒棒糖");
    }
}

三、Autowired注解,有三种形式的注解,分别是注解字段、构造器、setting。

package com.example.autowired;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.autowired.UserRepository;

@Service
public class UserService {
//    这个注释中的作用是使用Autowired去对字段进行注解
//    @Autowired
//    private UserRepository userRepository;


    private final UserRepository userRepository;

//  这个是对构造器进行注解
    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void save(){
        userRepository.save();
    }
}

复制

四、运行结果

package com.example.autowired;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class run {
    public static void main(String[] args) {
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService=(UserService) ctx.getBean("userService");
        userService.save();
    }
}

复制

需要些xml配置,autowired是通过xml注入的。

五、xml配置

<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
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.example.autowired">

</context:component-scan>
</beans>

复制

运行结果

22:08:01.334 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
22:08:01.342 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'userRepository'
22:08:01.346 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'userService'
22:08:01.357 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Autowiring by type from bean name 'userService' via constructor to bean named 'userRepository'
爱吃棒棒糖