Java – how to create different classes for database connections

I am developing a spring startup application. I need a general class to provide me with database connections for all controllers, so I created a seperate class as follows:

@RestController
public class DataBaseConnector{


     @Autowired
     @Qualifier("dataSource")
     public static DataSource dataSource;

        @Bean
        @Primary
        @ConfigurationProperties(prefix = "spring.ds")
        public DataSource DataSourcePGStreet() {
            return DataSourceBuilder.create().build();
        }

       @Autowired
       public Connection giveConnection() throws sqlException{
           return dataSource.getConnection();
       }


}

Then in another controller, I call the following connection:

@Autowired
    @Qualifier("dbc")
    private static DataBaseConnector obj;
@Autowired
 private Connection connectionDatabase;

.../// Rest Code
    @RequestMapping(value="/path",produces={MediaType.APPLICATION_JSON_VALUE},method=RequestMethod.GET)
     public ResponseEntity<?> getStreetscore(){


     obj=new DataBaseConnector();
     connectionDatabase=obj.giveConnection();



}

But it made me wrong

Use databaseconnector Error in any help creating name thank you

Full stack trace

Description:

Field dataSource in com.dmmltasmu.controller.DataBaseConnector required a bean of type 'javax.sql.DataSource' that Could not be found.
    - Bean method 'dataSource' not loaded because @ConditionalOnClass did not find required class 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType'
    - Bean method 'dataSource' not loaded because @ConditionalOnClass did not find required classes 'javax.transaction.TransactionManager','org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType'

Solution

You cannot assemble static fields automatically Ugly, but if you want to try less than one

@Component
public class AnotherController {

private static DataBaseConnectionProvider obj;

@Autowired
public void setDataBaseConnectionProvider(DataBaseConnectionProvider obj) {
    AnotherController.obj = obj;
}}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>