java之spring注解开发
1、xml形式
Person.java
package com.jackhu.bean;public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "com.jackhu.bean.Person{" +
"name="" + name + """ +
", age=" + age +
"}";
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
}
}
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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person" class="com.jackhu.bean.Person">
<property name="name" value="zh"/>
<property name="age" value="18"/>
</bean>
</beans>
MainTest.java
public class MainTest {public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
Person person = (Person) applicationContext.getBean("person");
System.out.println(person);
}
}
运行结果如下:
2、注解形式
/*** 配置类==配置文件
*
* @Configuration 告诉Spring这是一个配置类
* @Bean 给容器中注册一个Bean,类型为返回值类型,id默认是方法名作为id
*/
@Configuration
public class MainConfig {
@Bean("person")
public Person person2() {
return new Person("JACK", 18);
}
}
public class MainTest {public static void main(String[] args) {
// 1、xml形式
// ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
// Person person = (Person) applicationContext.getBean("person");
// System.out.println(person);
// 2、注解形式
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Person person = applicationContext.getBean(Person.class);
System.out.println(person);
String[] namesForType = applicationContext.getBeanNamesForType(Person.class);
for (String name : namesForType) {
System.out.println(name);
}
}
}
3、包扫描@ComponentScan
@Configuration@ComponentScan(value = "com.jackhu")
public class MainConfig {
@Bean("person")
public Person person2() {
return new Person("JACK", 18);
}
}
测试类
public class IOCTest {@Test
public void main() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
// 容器中所有bean名称
String[] names = applicationContext.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
}
}
增加组件标记
输出结果:
源码解析:
@Configuration@ComponentScan(value = "com.jackhu", excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class, Service.class}) // excludeFilters排除 Controller和Service注解不加进来
})
public class MainConfig {
@Bean("person")
public Person person2() {
return new Person("JACK", 18);
}
}
includeFilters同理
以上是 java之spring注解开发 的全部内容, 来源链接: utcz.com/z/511890.html