现在我们在新的包里定义两个 类。

ComponentDAO.java

package componentscan;

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

@Component
public class ComponentDAO {

	@Autowired
	ComponentJdbcConnection jdbcConnection;

	public ComponentJdbcConnection getJdbcConnection() {
		return jdbcConnection;
	}

	public void setComponentJdbcConnection(ComponentJdbcConnection jdbcConnection) {
		this.jdbcConnection = jdbcConnection;
	}
}

ComponentJdbcConnection.java

package componentscan;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;

@Component
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE, 
		proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ComponentJdbcConnection {
	public ComponentJdbcConnection() {
		System.out.println("JDBC Connection");
	}
}

DemoApplication.java

package con.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

import componentscan.ComponentDAO;

@SpringBootApplication
public class DemoApplication {

	private static Logger LOGGER =
			LoggerFactory.getLogger(DemoApplication.class);
	public static void main(String[] args) {
		
		
		
		ApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
		ComponentDAO bean1 = applicationContext.getBean(ComponentDAO.class);
		LOGGER.info("{}", bean1);
		LOGGER.info("{}", bean1.getJdbcConnection());

	}

}

现在我们执行程序,会发现报错了。

是因为我们的DemoApplication启动时会默认扫描

 package con.demo;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.context.ApplicationContext;
 
 import componentscan.ComponentDAO;
 
 @SpringBootApplication
 public class DemoApplication {
 
   private static Logger LOGGER =
       LoggerFactory.getLogger(DemoApplication.class);
   public static void main(String[] args) {
     
     
     
     ApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
     ComponentDAO bean1 = applicationContext.getBean(ComponentDAO.class);
     LOGGER.info("{}", bean1);
     LOGGER.info("{}", bean1.getJdbcConnection());
 
   }
 
 }
 

现在我们执行程序,会发现报错了。

是因为我们的DemoApplication启动时会默认扫描con.demo包。而我们新追加的类在componentscan包里,所以我们需要告诉Spring应该扫描的包是componentscan。

我们来介绍另外的一个注解@ComponentScan

@SpringBootApplication
@ComponentScan("componentScan")
public class DemoApplication {
	.....
}

下面我们来简单看一下**@ComponentScan**

@ComponentScan主要就是定义扫描的路径从中找出标识了需要装配的类自动装配到spring的bean容器中。

如果在@ComponentScan中指定了其他的包,当前的包将不会被扫描。