根据 【动力节点】最新Spring框架教程,全网首套Spring6教程,跟老杜从零学spring入门到高级 以及老杜的原版笔记 https://www.yuque.com/docs/share/866abad4-7106-45e7-afcd-245a733b073f?# 《Spring6》 进行整理, 文档密码:mg9b
Spring 相关文章整理汇总归纳于:https://www.yuque.com/u27599042/zuisie
// 标注该注解可以用在类上
@Target(ElementType.TYPE)
// 标注@Component注解最终保留在class文件当中,并且可以被反射机制读取。
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
// 定义注解的属性
// String是属性类型
// value是属性名
String value();
// 其他的属性
// 属性类型String
// 属性名是name
//String name();
// 数组属性
// 属性类型是:String[]
// 属性名:names
//String[] names();
//int[] ages();
//int age();
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
String value();
}
@Component("user")
public class User {}
@org.junit.Test
public void testGetAnnotationByReflect() throws Exception{
// 将类加载到JVM中
Class<?> clazz = Class.forName("cw.study.spring.bean.User");
// 判断类上是否有自定义的Component注解
if (clazz.isAnnotationPresent(Component.class)) {
// 如果有,获取该注解
Component component = clazz.getAnnotation(Component.class);
// 获取该类上注解的属性值
System.out.println(component.value());
}
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
String value();
}
@Component("user")
public class User {}
@Component("cat")
public class Cat {}
public class Person {}
@org.junit.Test
public void componentScan() {
// 已知的包名如下,需要扫描包下所有的类,将有Component注解的类实例化
String packageName = "cw.study.spring.bean";
// 包名其实就是目录名,将包名转化为目录
// . 在正则中代表任意字符,需要进行转义,而 \\ 表示 \ 所以使用 \\.
String directoryName = packageName.replaceAll("\\.", "/");
// 软件包是在类路径下的,所以可以使用系统加载器加载目录获取URL
URL url = ClassLoader.getSystemClassLoader().getResource(directoryName);
// 通过URL获取包对应的绝对路径
String path = url.getPath();
System.out.println("path = " + path);
// 根据绝对路径创建目录对应的对象
File file = new File(path);
// 获取目录下的文件对象
File[] files = file.listFiles();
System.out.println(files.length);
// 遍历每个文件对象
Arrays.stream(files).forEach(f -> {
try {
// 获取文件名
String fName = f.getName();
// System.out.println("fName = " + fName);
// 得到类名
String className = packageName + "." + fName.split("\\.")[0];
// 加载类到JVM
Class<?> clazz = Class.forName(className);
// 判断类上是否有Component注解
if (clazz.isAnnotationPresent(Component.class)) {
// 获取注解
Component component = clazz.getAnnotation(Component.class);
// 获取注解的属性(Bean的id)
String id = component.value();
System.out.println(id);
// 实例化对象
Object o = clazz.getDeclaredConstructor().newInstance();
System.out.println(o);
}
} catch (Exception e) {
e.printStackTrace();
}
});
}
@Target({ElementType.TYPE}) // 只能使用在类上
@Retention(RetentionPolicy.RUNTIME) // 可以通过反射获取该注解
@Documented
@Indexed
public @interface Component {
String value() default "";
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
// Component的别名
@AliasFor(
annotation = Component.class
)
String value() default "";
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
// Component的别名
@AliasFor(
annotation = Component.class
)
String value() default "";
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
// Component的别名
@AliasFor(
annotation = Component.class
)
String value() default "";
}
<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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
beans>
<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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="cw.study.spring"/>
beans>
@Component("user")
public class User {}
@Controller("userController")
public class UserController {}
@org.junit.Test
public void test01() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Object user = applicationContext.getBean("user");
Object userController = applicationContext.getBean("userController");
System.out.println(user);
System.out.println(userController);
}
@Component
public class User {}
@Controller
public class UserController {}
@org.junit.Test
public void test02() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Object user = applicationContext.getBean("user");
Object userController = applicationContext.getBean("userController");
System.out.println(user);
System.out.println(userController);
}
<context:component-scan base-package="cw.study.spring.bean, cw.study.spring.controller"/>
<context:component-scan base-package="cw.study.spring"/>
package cw.spring.bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
/**
* ClassName: A
* Package: cw.spring.bean
* Description:
*
* @Author tcw
* @Create 2023-05-14 11:42
* @Version 1.0
*/
@Component
public class A {
public A() {
System.out.println("A的无参数构造方法执行");
}
}
@Controller
class B {
public B() {
System.out.println("B的无参数构造方法执行");
}
}
@Service
class C {
public C() {
System.out.println("C的无参数构造方法执行");
}
}
@Repository
class D {
public D() {
System.out.println("D的无参数构造方法执行");
}
}
@Controller
class E {
public E() {
System.out.println("E的无参数构造方法执行");
}
}
:
<context:component-scan base-package="cw.spring.bean" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
:
<context:component-scan base-package="cw.spring.bean">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
String value();
}
package cw.spring.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* ClassName: MyDataSource
* Package: cw.spring.bean
* Description:
*
* @Author tcw
* @Create 2023-05-14 12:13
* @Version 1.0
*/
@Component
public class MyDataSource {
@Value("com.mysql.cj.jdbc.Driver")
private String driver;
@Value("jdbc:mysql://localhost:3306/spring")
private String url;
@Value("root")
private String username;
@Value("123456")
private String password;
@Override
public String toString() {
return "MyDataSource{" + "driver='" + driver + '\'' + ", url='" + url + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + '}';
}
}
package cw.spring.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* ClassName: MyDataSource
* Package: cw.spring.bean
* Description:
*
* @Author tcw
* @Create 2023-05-14 12:13
* @Version 1.0
*/
@Component
public class MyDataSource {
private String driver;
private String url;
private String username;
private String password;
@Value("com.mysql.cj.jdbc.Driver")
public void setDriver(String driver) {
this.driver = driver;
}
@Value("jdbc:mysql://localhost:3306/spring")
public void setUrl(String url) {
this.url = url;
}
@Value("root")
public void setUsername(String username) {
this.username = username;
}
@Value("123456")
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "MyDataSource{" + "driver='" + driver + '\'' + ", url='" + url + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + '}';
}
}
package cw.spring.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* ClassName: MyDataSource
* Package: cw.spring.bean
* Description:
*
* @Author tcw
* @Create 2023-05-14 12:13
* @Version 1.0
*/
@Component
public class MyDataSource {
private String driver;
private String url;
private String username;
private String password;
public MyDataSource(
@Value("com.mysql.cj.jdbc.Driver") String driver,
@Value("jdbc:mysql://localhost:3306/spring") String url,
@Value("root") String username,
@Value("123123") String password
) {
this.driver = driver;
this.url = url;
this.username = username;
this.password = password;
}
@Override
public String toString() {
return "MyDataSource{" + "driver='" + driver + '\'' + ", url='" + url + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + '}';
}
}
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
boolean required() default true;
}
/**
* ClassName: OrderDao
* Package: cw.spring.dao
* Description:
*
* @Author tcw
* @Create 2023-05-14 12:50
* @Version 1.0
*/
public interface OrderDao {
void insert();
}
/**
* ClassName: OrderDaoImplForMySQL
* Package: cw.spring.dao.impl
* Description:
*
* @Author tcw
* @Create 2023-05-14 12:50
* @Version 1.0
*/
@Repository
public class OrderDaoImplForMySQL implements OrderDao {
@Override
public void insert() {
System.out.println("MySQL数据库正在保存订单信息...");
}
}
import cw.spring.dao.OrderDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* ClassName: OrderService
* Package: cw.spring.service
* Description:
*
* @Author tcw
* @Create 2023-05-14 12:49
* @Version 1.0
*/
@Service("orderService")
public class OrderService {
@Autowired
private OrderDao orderDao;
public void save() {
orderDao.insert();
}
}
/**
* ClassName: OrderService
* Package: cw.spring.service
* Description:
*
* @Author tcw
* @Create 2023-05-14 12:49
* @Version 1.0
*/
@Service("orderService")
public class OrderService {
// @Autowired
// @Qualifier("orderDaoImplForOracle")
private OrderDao orderDao;
public OrderService(OrderDao orderDao) {
this.orderDao = orderDao;
}
public void save() {
orderDao.insert();
}
}
/**
* ClassName: OrderDaoImplForOracle
* Package: cw.spring.dao.impl
* Description:
*
* @Author tcw
* @Create 2023-05-14 12:59
* @Version 1.0
*/
@Repository
public class OrderDaoImplForOracle implements OrderDao {
@Override
public void insert() {
System.out.println("Oracle数据库正在保存订单信息...");
}
}
/**
* ClassName: OrderService
* Package: cw.spring.service
* Description:
*
* @Author tcw
* @Create 2023-05-14 12:49
* @Version 1.0
*/
@Service("orderService")
public class OrderService {
@Autowired
@Qualifier("orderDaoImplForOracle")
private OrderDao orderDao;
public void save() {
orderDao.insert();
}
}
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Resources.class)
public @interface Resource {
String name() default "";
String lookup() default "";
Class<?> type() default Object.class;
AuthenticationType authenticationType() default Resource.AuthenticationType.CONTAINER;
boolean shareable() default true;
String mappedName() default "";
String description() default "";
public static enum AuthenticationType {
CONTAINER,
APPLICATION;
private AuthenticationType() {
}
}
}
<dependency>
<groupId>jakarta.annotationgroupId>
<artifactId>jakarta.annotation-apiartifactId>
<version>2.1.1version>
dependency>
<dependency>
<groupId>javax.annotationgroupId>
<artifactId>javax.annotation-apiartifactId>
<version>1.3.2version>
dependency>
/**
* ClassName: StudentDao
* Package: cw.spring.dao
* Description:
*
* @Author tcw
* @Create 2023-05-14 16:03
* @Version 1.0
*/
public interface StudentDao {
void deleteById();
}
/**
* ClassName: StudentDaoImplForMySQL
* Package: cw.spring.dao.impl
* Description:
*
* @Author tcw
* @Create 2023-05-14 16:04
* @Version 1.0
*/
@Repository
public class StudentDaoImplForMySQL implements StudentDao {
@Override
public void deleteById() {
System.out.println("MySQL数据库正在删除学生信息...");
}
}
/**
* ClassName: StudentService
* Package: cw.spring.service
* Description:
*
* @Author tcw
* @Create 2023-05-14 16:05
* @Version 1.0
*/
@Service
public class StudentService {
// name属性用于指定将要被注入到该属性的Bean的名字
@Resource(name = "studentDaoImplForMySQL")
private StudentDao studentDao;
public void delete() {
studentDao.deleteById();
}
}
@Configuration
public class Spring6Config {
}
@Configuration
@ComponentScan({"cw.spring.dao", "cw.spring.service"})
public class Spring6Config {
}
new ClassPathXmlApplicationContext()
对象了,而是 new AnnotationConfigApplicationContext()
@org.junit.Test
public void test03() {
// 获取Spring容器对象时,需要传配置类为参数
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Spring6Config.class);
StudentService studentService = applicationContext.getBean("studentService", StudentService.class);
studentService.delete();
}