1、XML 配置文件。
Bean 所需的依賴項和服務在 XML 格式的配置文件中指定。這些配置文件通常包含許多 bean 定義和特定於應用程序的配置選項。它們通常以 bean 標簽開頭。例如:
<bean id="studentBean" class="org.edureka.firstSpring.StudentBean">
<property name="name" value="Edureka"></property>
</bean>
2、注解配置。
您可以通過在相關的類,方法或字段聲明上使用注解,將 Bean 配置為組件類本身,而不是使用 XML 來描述 Bean 裝配。默認情況下,Spring 容器中未打開注解裝配。因此,您需要在使用它之前在 Spring 配置文件中啟用它。例如:
<beans> <context:annotation-config/> <!-- bean definitions go here --> </beans>
@Service @Component @Repository @Controlle
3、Java Config 配置。
Spring 的 Java 配置是通過使用 @Bean 和 @Configuration 來實現。
@Bean注解扮演與<bean />元素相同的角色。用到方法上,表示當前方法的返回值是一個bean@Configuration類允許通過簡單地調用同一個類中的其他@Bean方法來定義 Bean 間依賴關系。相當於spring的配置文件XML
例如:
@Configuration
public class StudentConfig {
@Bean
public StudentBean myStudent() {
return new StudentBean();
}
}
這幾種方式沒有什么所謂的優劣之分,主要看使用情況,一般來說是這樣:
涉及到全局配置的,例如數據庫相關配置、MVC相關配置等,就用Java Config 配置的方式
涉及到業務配置的,就使用注解方式
*****************************************************************************
*****************************************************************************
Java Config 配置 解釋:https://blog.csdn.net/peng86788/article/details/81188049
定義 JavaConfig 類 對於一個 POJO 類,在類上使用@Configuration 注解,將會使當前類作為一個 Spring 的容器來使用,用於完成 Bean 的創建。在該 JavaConfig 的方法上使用@Bean,將會使一個普通方法所返回的結果變為指定名稱的 Bean 實例。
package com.lzl.spring.entity;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//該注解表示這個類為javaConfig類
@Configuration
public class MyConfig {
//該注解表示:向容器中注冊一個叫做myCar的對象
@Bean("myCar")
public Car getCar() {
return new Car("保時捷","911",300);
}
//該注解表示:向容器中注冊一個叫做person的對象
//並且通過byType的方式注入car
@Bean(name="person",autowire=Autowire.BY_TYPE)
public Person getPerson() {
return new Person(1001,"望穿秋水見伊人");
}
}
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"
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="com.lzl.spring" />
</beans>
測試類
package com.lzl.spring.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.lzl.spring.entity.Car;
import com.lzl.spring.entity.Person;
public class SpringTest {
@Test
public void test1() {
//讀取配置文件
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-config.xml");
Car car = ctx.getBean("myCar", Car.class);
System.out.println(car);
Person person = ctx.getBean("person", Person.class);
System.out.println(person);
}
}
控制台輸出

