推荐文档: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'
爱吃棒棒糖
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。